useRef Hook

🪝 Introduction to useRef

The useRef Hook is a React Hook that creates a mutable reference object whose value persists across component re-renders. Unlike useState, updating a ref does not trigger a component re-render, making it ideal for storing mutable values and interacting directly with DOM elements.

Important

useRef returns an object with a single property named current. React preserves the same ref object for the entire lifetime of the component.

🎯 Why Use useRef?

Some values need to persist between renders without affecting the UI. Similarly, React applications often need direct access to DOM elements for focusing inputs, controlling videos, or measuring element sizes.useRef provides a clean way to handle these scenarios.

  • Access DOM elements directly.
  • Store mutable values without re-rendering.
  • Persist values across renders.
  • Keep previous values or timer IDs.

⚙️ Syntax

Basic Syntax

const ref = useRef(initialValue);
PartDescription
initialValueThe initial value assigned to the ref.
ref.currentThe mutable value stored inside the ref object.

🔄 How useRef Works

Create a Ref
React Creates a Ref Object with current
Attach It to a DOM Element or Store Data
Read or Update the current Property
Updating current Does Not Re-render the Component

💻 Step 1: Create a Ref

Creating a Ref

import { useRef } from "react";

function App() {
  const inputRef = useRef(null);
}

Calling useRef() creates a ref object whose current property initially contains the supplied value.

💻 Step 2: Attach the Ref

Attach to an Element

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

  return <input ref={inputRef} />;
}

The ref attribute connects the DOM element to the ref object, allowing React to store the element in inputRef.current.

💻 Step 3: Use the Ref

Focus an Input

import { useRef } from "react";

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

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

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus</button>
    </>
  );
}

Calling methods on inputRef.current lets you interact with the DOM element directly.

📊 useState vs useRef

Updating state causes React to re-render the component so the UI stays in sync with the latest data.

Updating ref.current does not trigger a re-render, making it suitable for mutable values and DOM references.

📋 Ref Lifecycle

Component Renders
Create Ref Object
React Assigns DOM Element to current
Read or Update current
Component Re-renders
Same Ref Object Is Preserved

🌍 Common Use Cases

ScenarioPurpose
Focus InputAutomatically focus form fields.
Store Timer IDKeep interval or timeout identifiers.
Previous ValueRemember previous state values.
DOM ManipulationScroll, measure, or control elements.
Third-party LibrariesAccess DOM nodes required by external APIs.

🧩 Combining useRef with useEffect

A common pattern is combining useRef with useEffect to focus an element immediately after the component mounts.

Auto Focus Input

import { useEffect, useRef } from "react";

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

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} />;
}

⚠️ Common Mistakes

  • Expecting changes to ref.current to re-render the UI.
  • Using refs instead of state for UI data.
  • Accessing current before the element is mounted.
  • Overusing refs when props or state are sufficient.

Warning

Changes to ref.current are not tracked by React's rendering system. Use useState whenever UI updates are required.

✅ Best Practices

  • Use refs primarily for DOM access.
  • Store mutable values that should persist between renders.
  • Keep component state in useState.
  • Combine useRef with useEffect for DOM interactions after rendering.
  • Avoid unnecessary direct DOM manipulation.

📚 Official Resource

Learn more about useRef in the official React documentation at React useRef Documentation.

Summary

The useRef Hook provides a persistent mutable reference object that survives component re-renders without triggering additional renders. It is commonly used for accessing DOM elements, storing mutable values, managing timers, and preserving previous values. When used appropriately, useRef helps build efficient, performant, and well-structured React applications.