What is useRef Hook in React

This article provides a clear overview of the useRef hook in React, explaining its purpose, core characteristics, and primary use cases. You will learn how useRef allows you to persist values across renders without triggering UI updates, how to use it to directly access and manipulate DOM elements, and how it differs from the standard useState hook.

Understanding useRef

The useRef hook is a built-in React hook that returns a mutable “ref” object. This object has a single property called .current, which is initialized with the argument you pass to the hook (e.g., useRef(initialValue)).

The defining characteristic of useRef is that updating the .current property does not trigger a component re-render. This makes it fundamentally different from useState, where updating state always forces React to re-render the component and update the UI.

Primary Use Cases

There are two main scenarios where you should use the useRef hook in your React applications:

1. Accessing and Manipulating DOM Elements

In React, you typically let the library handle DOM updates. However, sometimes you need direct access to a DOM node—for example, to focus an input field, measure an element’s size, or trigger an animation.

By passing the ref object to a JSX element’s ref attribute, React will set the .current property to the corresponding DOM node once it renders.

2. Storing Mutable Values (Without Re-renders)

If you need to keep track of a value that changes over time, but that value has no impact on the visual output of the component, useRef is the ideal choice. Examples include: * Storing interval or timeout IDs so you can clear them later. * Counting how many times a component has rendered. * Storing the previous value of a state variable.

Code Example: Focusing an Input

The following example demonstrates how to use useRef to directly access a DOM element and focus an input field when a button is clicked:

import React, { useRef } from 'react';

function FocusInput() {
  // 1. Initialize the ref with null
  const inputRef = useRef(null);

  const handleClick = () => {
    // 3. Access the DOM node via .current and call focus()
    inputRef.current.focus();
  };

  return (
    <div>
      {/* 2. Attach the ref to the input element */}
      <input ref={inputRef} type="text" placeholder="Click button to focus..." />
      <button onClick={handleClick}>Focus the input</button>
    </div>
  );
}

export default FocusInput;

Summary: useRef vs useState

Feature useState useRef
Triggers Re-render? Yes, when the state value changes. No, when the .current value changes.
Value Persistence Persists across renders. Persists across renders.
Best Used For Data that determines what is rendered on the screen. DOM manipulation, storing IDs, and tracking non-visual data.