Learn the useRef Hook in React

Learn the useRef Hook in React

What is the useRef hook?

The useRef hook is one of the most used hooks in react. It returns an object with a single property called .current.

With useRef, you can do the following.

  • Access the DOM elements.
  • Access data that persist across re-renders.
  • Store mutable values without triggering a re-render when the value changes.

useRef vs useState

A significant difference between useRef and useState is the re-rendering of components.

With useState, an update in state variables causes components to re-render.

The useRef hook doesn't trigger the re-render of components when values change.

If you don't want your component to re-render when a value changes, using useRef is a safe bet.

Syntax for useRef hook

Like other hooks in React, to use useRef, you first have to import it.

import { useRef } from 'react'

And use it inside your functional components.

const myRef = useRef(initialValue)

The useRef hook returns an object. The object has a special property called current. The value of the current property is initialValue.

For example, myRef would be equal to an object like so.

{ current: initialValue }

Using useRef to access DOM elements

A use case for useRef in React is to access DOM elements. Every DOM element has a ref property. You can set the value of an element's ref property to a reference object (created using useRef).

An example is if you want to focus on an input element when a user clicks a button.

import { useRef } from "react";

function ExampleComponent() {
 const inputRef = useRef(null);

 const setFocus = () => {
   inputRef.current.focus();
 };

 return (
   <div>
     <input ref={inputRef} />
     <button onClick={setFocus}>Start Typing</button>
   </div>
 );
}

Run Example Code

Here's a breakdown of what is happening in the code sample above.

First, you import the useRef hook from React.

In the ExampleComponent, you return a div containing an input element and a button.

The input element (like all other DOM elements) has a ref property. And in this case, you assign inputRef as the value of the ref property.

inputRef has an initial value of null. When the DOM elements renders, the value of inputRef's current property changes from null to an object like so.

{ current: <input /> }

With this, you now have direct access to the <input /> DOM element. That is why you can apply the focus method on the element.

 const setFocus = () => {
   inputRef.current.focus()
 }

Using useRef to track state values

The useRef hook does more than help you access DOM elements. Using useRef, you can persist data between renders. This means you can use the useRef hook to store previous values of state variables.

Here is an example of such a use case below.

import { useState, useEffect, useRef } from "react";

function WordComponent() {
  const [word, setWord] = useState("Hello");
  const previousWord = useRef(null);

  useEffect(() => {
    previousWord.current = word;
  }, [word]);

  return (
    <>
      <input 
        value={word} 
        onChange={(e) => setWord(e.target.value)} 
      />
      <h3>Current word: {word}</h3>
      <h3>Previous word: {previousWord.current}</h3>
    </>
  );
}

Run Example Code

With useRef, you can track the previous value of the word variable. An update in the word variable causes an update in the previousWord variable.

The dependency array in useEffect contains the word variable. Whenever word changes, it will trigger useEffect to run. And this updates the current value of the previousWord ref.

Conclusion

The useRef hook is one of the most common hooks in React. Getting a good grasp of it will help you become a better React developer. As you have learned in this tutorial, it is used for accessing DOM elements . And it can also help to to keep track of previous values of a state variable.