Skip to main content

Command Palette

Search for a command to run...

useRef hook

Published
•2 min read•View as Markdown
useRef hook

Let us now learn about a new react hook which is the useRef hook The syntax of the useRef hook let dhruv=useRef(1); From the above syntax we notice that useRef function returns an object and the object looks like

dhruv={current:1}

Thus the object only contains one key which is the current value

Use of useRef?

Lets say we have a code sample:

image.png

image.png

Hence we can say that useRef returns an object which is mutable but on changing the object it doesn't lead to a re-render unlike useState

Why is useRef useful? 1)storing mutating information in your app without triggering a re-render. 2) interacting with DOM elements

The task done by the useRef can also be done by taking a global object and using this global object inside the function. However with useRef one gets the advantage of garbage collection i.e when the component containing the useRef is not mounted to the ui in that case it doesn't take up any memory space unlike the global variable object which consumes memory even if the component is not used.

image.png

In the above example despite mutating the dhruv object the function doesn't re-render again

image.png

The other important useCase of useRef is that we can perform DOM manipulation in react using useRef. How?

Let us see an example:

image.png

hence from the above example we can store the tag objects inside the dhruv useRef object

The output of the above code will be:

image.png

One thing to keep in mind while using useRef for DOM manipulation is that when the component is lets say not mounted to the UI then in that case if we are using the ref object on any tag the tag will be undefined in the useRef object

image.png

The above code will generate an error when we try to access the innerText of the dhruv.current because here the current is undefined

Uncaught TypeError: Cannot set properties of undefined (setting 'innerText') at App.jsx:11:23

Another USE CASE of the useRef hook is that we can count the number of re-renders using the useRef hook

image.png

image.png

More from this blog

Dhruv's Web development journey

64 posts