Demystifying useRef hook.

Demystifying useRef hook.

Before diving into useRef() hook, we should first understand what refs are. As per the definition from ReactJS official docs

Refs provide a way to access DOM nodes or React elements created in the render method.

Let’s look at what react docs meant by “a way to access DOM nodes”.

Assume we have an input tag and we pass a variable named inputRef to its ref attribute <input ref={inputRef} />. The purpose of this attribute is to make the input element selectable so that we can access its values, change styles, add animations, etc. This might seem familiar with the HTML id attribute because ids give us access to DOM nodes too. So, how are refs different then? Well, the difference arises when we want to reuse the same component multiple times with different prop values as I have shown below: idExample.png

I have used id to change the style property here but when you run this code, you will see that the input border color for all three<Demo/> components changes to blue because that is what I have passed as a prop in the last declaration. But if we were to use ref here then all the three components will render different border colors as received in their props because ref exists only in the scope of that component. This unique ability of refs to access and manipulate DOM nodes without messing with the entire DOM tree is what sets it apart from the HTML id attributes.

Now let’s take a look at that inputRef variable we passed earlier. Do we define any variable and pass it to the ref just like that? No, because that will just get reset when the component will re-render. This is where the hook useRef() comes into the picture. Calling this react hook returns a mutable object with a .current property which is initialized with whatever argument we passed as its initial value.

When we pass this object as ref to a DOM node as we did with our input element then React will set its .current property to the corresponding node.

There are a bunch of things you can do after targeting a node once the DOM loads like adding some animation or other styles. It comes in handy when using third-party DOM libraries in your code. domRef.png

Now let’s look at another popular use case of this hook. The mutable object that useRef() returns persists through the entire lifetime of the component which means no matter how many times the component re-renders due to state changes, the .current property value won’t change (unless we explicitly do it). This makes it perfect to store any value which we want to persist through re-renders and can also be used for if/else conditions without being worried about it being affected by state changes. Here is an example:

valueRef.png

Hope this small article helped you clear some of the doubts you had with ref attributes and the useRef() hook.