How to use React.useRef hook

Backend developer with strong experience in the .NET ecosystem and AWS. Other development skills include JavaScript/React/Vue, HTML, CSS.
Search for a command to run...

Backend developer with strong experience in the .NET ecosystem and AWS. Other development skills include JavaScript/React/Vue, HTML, CSS.
No comments yet. Be the first to comment.
According to the React docs: useDebugValue is a React Hook that lets you add a label to a custom Hook in React DevTools. When do I need useDebugValue? useDebugValue becomes important when you implement a custom hook. For example, let's say you have...

Understand what really happens when you don't pass the key prop when rendering a list in React

Implement AWS Cognito authentication using Authorization Code Grant with hosted UI into your Nextjs application

Start writing your own Cypress tests in React

According to the React docs:
useRefis 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
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.
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.
Hopefully, you should now have a good understanding of when and how you should use the useRef hook.