How to Update useRef Hook in React

The useRef hook is a powerful tool in React that allows you to persist values across renders without triggering a re-render. This article provides a straightforward guide on how to update the value of a useRef hook, explaining the syntax, showing practical code examples, and highlighting the key rules to follow when mutating ref values.

To update a useRef hook in React, you directly mutate its .current property. Unlike state variables managed by useState, changing the value of a ref does not cause your component to re-render.

The Syntax for Updating useRef

When you initialize a ref using useRef(initialValue), React returns a mutable object with a single property: current.

const myRef = useRef(initialValue);

To update this value, you simply assign a new value directly to myRef.current:

myRef.current = newValue;

Example 1: Persisting a Mutable Value

Because updating a ref does not trigger a re-render, it is ideal for tracking values that do not affect the visual output of the component, such as interval IDs or click counters.

import { useRef } from 'react';

function ClickCounter() {
  const clickCount = useRef(0);

  const handleClick = () => {
    clickCount.current = clickCount.current + 1;
    console.log(`Button clicked ${clickCount.current} times`);
  };

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

In this example, every time the button is clicked, clickCount.current increases by 1. The value is successfully updated and persisted, but the component does not undergo a costly re-render.

Example 2: Accessing and Updating DOM Elements

The most common use case for useRef is to reference and manipulate DOM nodes directly. When you pass a ref object to a React element, React automatically updates the .current property to point to the corresponding DOM node when the component mounts.

import { useRef } from 'react';

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

  const handleFocus = () => {
    // Accessing and updating the DOM element directly
    inputRef.current.focus();
    inputRef.current.value = "Updated text!";
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleFocus}>Focus and Update Input</button>
    </div>
  );
}

Here, inputRef.current initially holds null. Once the component mounts, React sets inputRef.current to the <input> DOM element, allowing you to trigger focus and update its value directly.

Best Practices When Updating useRef