ReactJS useRef Hook

In React, not every value needs to update the UI when it changes. Some values only need to be remembered or used internally, without triggering a re-render. The useRef Hook exists exactly for these situations.


What Is useRef?

useRef is a React Hook that allows you to store a value that persists across renders without causing the component to re-render when it changes.

In simpler words:

useRef is used to remember values between renders without updating the UI.

It returns an object with a single property:

{ current: value }


Why Does React Need useRef?

React components are just functions.
Every time a component re-renders, the function runs again from the top.

Because of this:
  • normal variables reset on every render
  • state values are tracked and trigger re-renders
But sometimes you need:
  • a value that should not reset
  • a value that should not cause re-render
  • direct access to a DOM element
useRef solves all of these problems.

Importing useRef


import { useRef } from "react";


Basic Syntax of useRef


const myRef = useRef(initialValue);

  • initialValue is set only once (on first render)
  • the value is stored in myRef.current
  • updating myRef.current does not re-render the component

Accessing DOM Elements (Most Common Use Case)

React does not encourage direct DOM access using document.getElementById.
Instead, it provides useRef for safe DOM interaction.

Example: Focus an Input Field

import { useRef } from "react";

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

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

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

export default FocusInput;

Explanation
  • React stores the input element in inputRef.current
  • You can call DOM methods safely
  • UI does not re-render

When You Should Use useRef

Use useRef when you need to:

  • access DOM elements
  • store mutable values
  • remember previous state
  • avoid unnecessary re-renders
  • Scroll to a Section
  • Prevent Multiple API Calls

Final Summary

The useRef Hook allows React components to store values that persist across renders without triggering UI updates. It is commonly used for DOM access, tracking previous values, managing timers, and storing internal mutable data. Understanding useRef helps you write more efficient and predictable React components by avoiding unnecessary re-renders.