useRef Hook in React

useRef Hook in React

In React, Hooks introduced to make presentation/Stateless component, (Functional Component) to Stateful Component.

Hooks are really amazing to learn about. So far I have used various hooks like useState, useEffect, useReducer, useHistory, useLocation and many more. UseRef is something which i never used and always wanted to learn about. Today I finally able to understand what exactly use-case of useRef. With the help of this blog, I am sharing whatever i Learnt as "SHARING IS CARING".

useRef is a hook which returns an object whose current property is the value which we pass in useRef().

eg:
const inputRef=useRef(initialValue).

inputRef is a object whose current property is equal to initialValue. inputRef={current:initialValue}

UseCase of useRef:

  • If you already aware about useState hook then you might know that at every state update component re-renders. so here comes in useRef if you don't want to re-render component even after update

    Let's analyse an example without use of useRef() :

Screenshot 2021-12-11 at 5.37.23 PM.png

In this example, Whenever we click on button state update and then component re-render and again state update and component re-render and it will throw ERROR (Maximum update depth exceeded)

Screenshot 2021-12-11 at 5.34.13 PM.png

In this example, Whenever we click on button, count update and then component won't re-render and every time whenever we click on button, only variable will update.

  • If you want to render current value and previous value then useRef can help as shown in example below:

Screenshot 2021-12-11 at 5.59.52 PM.png

In this example whenever state update component re-render and then assigning that value in ref variable which basically render previous value of state.

  • Mostly useRef hooks are used in HTML elements while providing ref property to input tag as shown in below example :

Screenshot 2021-12-11 at 6.04.17 PM.png

In this example every time whenever we will click on focus button, Focus will be seen to input Field.

These are the main use-case of useRef(). Hopefully this blog may help to understand useRef() hook more clearly.