DEV Community

Cover image for useRef Hook in React
Mahalakshmi C
Mahalakshmi C

Posted on

useRef Hook in React

useRef is a React Hook that is used to store a value that persists between renders without causing the component to re-render when the value changes.

It is also commonly used to access and interact with DOM elements directly.

Syntax

const reference = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

For example:

const count = useRef(0);
Enter fullscreen mode Exit fullscreen mode

What Does useRef Return?

useRef() returns an object containing a property called current.

const count = useRef(0);

console.log(count);
Enter fullscreen mode Exit fullscreen mode

The result is similar to:

{
    current: 0
}
Enter fullscreen mode Exit fullscreen mode

The value can be accessed or changed using:

count.current
Enter fullscreen mode Exit fullscreen mode

For example:

count.current = count.current + 1;
Enter fullscreen mode Exit fullscreen mode

Why Do We Use useRef?

useRef is commonly used for:

  1. Accessing DOM elements
  2. Storing values between renders
  3. Keeping a previous value
  4. Storing values without causing a re-render

Example 1: Accessing a DOM Element

One of the most common uses of useRef is focusing an input element.

import { useRef } from "react";

function App() {

    const inputRef = useRef();

    function focusInput() {
        inputRef.current.focus();
    }

    return (
        <div>
            <input ref={inputRef} />

            <button onClick={focusInput}>
                Focus Input
            </button>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

How does it work?

First, we create a ref:

const inputRef = useRef();
Enter fullscreen mode Exit fullscreen mode

Then we attach it to the input:

<input ref={inputRef} />
Enter fullscreen mode Exit fullscreen mode

React stores the input DOM element inside:

inputRef.current
Enter fullscreen mode Exit fullscreen mode

When the button is clicked:

inputRef.current.focus();
Enter fullscreen mode Exit fullscreen mode

the input receives focus.


Example 2: useRef Does Not Cause Re-render

Consider:

const count = useRef(0);
Enter fullscreen mode Exit fullscreen mode

We can change the value:

count.current = count.current + 1;
Enter fullscreen mode Exit fullscreen mode

But changing count.current does not cause the component to re-render.

This is an important difference between useRef and useState.

useState useRef
Stores state Stores a mutable reference
Updating state causes re-render Updating .current does not cause re-render
Uses a setter function Uses .current
Used when UI needs to update Useful when UI does not need to update

useRef for Storing Previous Values

useRef can also be used to remember a value from the previous render.

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

function App() {

    const [name, setName] = useState("Maha");
    const previousName = useRef("");

    useEffect(() => {
        previousName.current = name;
    }, [name]);

    return (
        <div>
            <h2>Current Name: {name}</h2>
            <h2>Previous Name: {previousName.current}</h2>

            <button onClick={() => setName("Lakshmi")}>
                Change Name
            </button>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Here, previousName.current can store a value that persists between renders.


useRef vs useState

Suppose we have:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

When we write:

setCount(count + 1);
Enter fullscreen mode Exit fullscreen mode

React updates the state and re-renders the component.

But with:

const count = useRef(0);
Enter fullscreen mode Exit fullscreen mode

when we write:

count.current = count.current + 1;
Enter fullscreen mode Exit fullscreen mode

the value changes, but React does not re-render the component just because the ref changed.

Simple Flow

useState

State changes
     ↓
React re-renders
     ↓
UI updates
Enter fullscreen mode Exit fullscreen mode

useRef

ref.current changes
     ↓
No automatic re-render
     ↓
Component UI does not automatically update
Enter fullscreen mode Exit fullscreen mode

Conclusion

useRef is useful when a value needs to persist between renders without triggering a re-render. It is especially useful for accessing DOM elements, storing previous values, and keeping mutable values that do not directly control the UI.

Top comments (0)