How to Update React Refs

This article provides a quick overview of how to update React Refs in functional components. You will learn how to create refs using the useRef hook, update their values, and safely manipulate DOM elements or store mutable variables without triggering component re-renders.

What is a React Ref?

A ref is an object with a single mutable property called current. React provides the useRef hook to create this object. Unlike state variables, updating a ref does not cause your component to re-render.

Refs are commonly used for two main purposes: 1. Storing mutable values that do not affect the visual output of the component. 2. Directly accessing and manipulating DOM nodes.

Updating Mutable Values with Refs

To update the value stored inside a ref, you directly reassign its current property. Because this update does not trigger a re-render, it is ideal for tracking values like interval IDs, counter variables, or previous state values.

Here is an example of updating a mutable value using a ref:

import { useRef } from 'react';

function Timer() {
  const countRef = useRef(0);

  const handleIncrement = () => {
    // Directly update the ref value
    countRef.current = countRef.current + 1;
    console.log(`Clicked ${countRef.current} times`);
  };

  return (
    <button onClick={handleIncrement}>
      Increment (Check Console)
    </button>
  );
}

Updating and Accessing DOM Nodes

When you pass a ref to a JSX element via the ref attribute, React automatically updates the current property of that ref with the corresponding DOM node once the component mounts. When the component unmounts, React sets it back to null.

Here is how you access and update DOM properties using a ref:

import { useRef } from 'react';

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

  const handleFocus = () => {
    // Access and update the DOM element directly
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

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

Best Practices for Updating Refs

To keep your application predictable, adhere to the following rules when updating refs: