How to use useRef in React

useRef is one of the most important hooks in React, as it helps developers implement a number of dynamic features for interactive apps.

It works like a function that accepts one argument – the initial value of the ref. When invoked, the function returns an instance of a ref that can hold a value. Usually it holds a DOM element so you can reference that element in your JavaScript code. Ref also has unique feature that changes do not trigger a re-render. That’s why many developers use refs to store values without unnecessary re-renders.

useRef in practice

Let’s discuss the most common use case for useRef in React – to reference a DOM element in a functional or class component. This use case is very common, and comes up whenever you need to work with DOM elements directly. Sometimes we call methods on these elements, or change their inner HTML value.

To start, you should import useRef from the main library:

import React, { useRef } from 'react';

const myElement = useRef(null);

Next step should be to create a variable and set to a useRef() call. The hook returns instance of an empty ref (because of the null argument). This is exactly what we need, because we’re going to associate the ref with a specific element in the DOM.

To do this, you need to locate JSX returned by the function component. Then select the element you want to create ref for and set its ref attribute to name of the variable.

return <div ref={myElement}>Hello, world!</div>;

From this point on, you will be able to access the div element on myElement.current. This works similar to how you might use getElementById() to access element and store it in a variable. Then you can use this variable to call DOM element’s methods or update its properties. You can use refs on as well.

Or you can simply log it to the console to see what it is.

console.log(myElement.current.getBoundingClientRect())

Important feature of refs is that changes to the variable do not trigger the component to update. So you can store something in a ref and be assured that the value will not change after re-renders.

When to use useRef hook (and when not to)

We have covered all the benefits of useRef hook, but using it comes with risks. First, let’s discuss when it’s a good idea to use this hook:

  • To directly access a DOM element, store it in a variable and modify its contents or call methods.

  • As a way to persist mutable data between component updates.

  • To maintain a mutable value without triggering a re-render every time it changes.

This is when you should NOT use the hook:

  • When you use the value in your JSX. In this case, component should update when the value changes, and you’d be better off using useState or useReducer instead.

  • As a workaround to synchronize state with props. React does this automatically and if you need to do this, there’s a bug in your code.

Let’s refresh our memory of useRef hook:

  • It’s used to create mutable variables in functional components.

  • Changes to ref values do not update the component. Forgetting this point can lead to wrong use of the useRef hook.

In summary, useRef() can be useful or it can be harmful depending on your use-cases.

useRef vs getElementById

There are two ways to do DOM manipulation in React. You can use either the getElementById method or the useEffect() hook. Both of these achieve the same result – store a reference to DOM element in a variable. However, they are used differently. One of them has many valid use-cases in React, while the other is usually not the right tool for the job.

document.getElementById is a well-known JavaScript method for selecting elements by passing their ID as argument. It is commonly used in jQuery, which is why many developers are curious about if it can be used in React. The answer is no. It’s almost always not the right tool to use in React. Mainly because React ecosystem is built around declarative code, whereas getElementByID is imperative.

useRef is a hook specifically built for React. It can be said that useRef exists specifically to replace getElementById in React. It allows you to reference DOM elements in React. As you know, React does not use real DOM, it uses virtual DOM. You can’t use getElementById() to interact with virtual DOM, but you can use useRef.

useRef is well-integrated into the React ecosystem and rendering cycle. Also, unlike getElementById(), it doesn’t require you to have unique id s on your components and elements. This allows you to reuse components without worrying about unique IDs.

Difference between refs and state variables is that changes to the former does not trigger a re-render. But changes to the state do. For this reason, we use refs to store mutable values that do not rely on render output.

In conclusion, while getElementById can be used in React, it's not a good practice to do so. In practice, you should use useRef to interact with DOM elements in React. You can use it to stay true to React ecosystem and library principles.

Final words

In summary, useRef is an extremely useful feature of React. You can use it to implement interactive features like scroll to bottom when user clicks a button, or highlight a certain element. Best of all, it doesn’t get in the way of how we do things in React.