According to the React docs:
useRef
is a React Hook that lets you reference a value that’s not needed for rendering.
Here are two examples where useRef
should be used:
Referencing a value with a ref
Manipulating the DOM with a ref
Referencing a value with a ref
The most common example of referencing a value would be either setTimeout
or setInterval
.
setInterval
is a global javascript function that will call a callback function at a defined interval. When you initialise the interval function, it will continue running until you call clearInterval
.
const intervalId = setInterval(callback, 1000);
To clear the interval, you will need to use the returned intervalId
.
clearInterval(intervalID);
In a React component, you will need to retain intervalId
between renders. By using useRef
, the component can store the intervalId
until it clears the interval.
Manipulating the DOM with a ref
It is bad practice to directly manipulate the DOM in React. It can cause performance issues and unexpected side effects. However, you may need to use a library that needs to access the DOM.
As an example, let's say you decide to use the library AnimeJs to add javascript animations to your application. However, AnimeJs is a vanilla javascript library, so we will need to find a way to integrate it into the React application.
The documentation provides the following basic example of an animation.
anime({
targets: '.css-selector-demo .el',
translateX: 250
});
To integrate this code with React, we can very easily replace the targets with useRef
. First, initialise useRef
within the component.
const element = React.useRef(null);
Next, pass element
into the relevant element.
<div ref={element}></div>
Finally, update the animation call to reference element.current
. The current
property holds a reference to a value that persists across re-renders of the component.
anime({
targets: element.current,
translateX: 250
});
Below is a working example with AnimeJs.
Conclusion
Hopefully, you should now have a good understanding of when and how you should use the useRef
hook.