Menu

React useRef: DOM Access, Persistent Values & Examples

useRef DOM Access and Persistent Values

What is useRef?

useRef returns an object with a single .current property. That object survives across re-renders, and changing .current does not trigger a re-render.

It has two distinct uses.

Use 1: Accessing a DOM Element

jsx

import { useRef } from "react";

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

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

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="Search courses" />
      <button onClick={handleFocus}>Focus the search box</button>
    </div>
  );
}

export default SearchBar;
  • ref={inputRef} attaches the ref to the element.
  • inputRef.current is then the actual DOM node, so you can call .focus(), .scrollIntoView(), .play(), and so on.
  • It starts as null because the element does not exist until after the first render.

Use 2: Storing a Value Without Re-Rendering

jsx

import { useState, useRef, useEffect } from "react";

function QuizTimer() {
  const [timeLeft, setTimeLeft] = useState(60);
  const intervalRef = useRef(null);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setTimeLeft(prev => prev - 1);
    }, 1000);

    return () => clearInterval(intervalRef.current);
  }, []);

  function handlePause() {
    clearInterval(intervalRef.current);
  }

  return (
    <div>
      <p>Time left: {timeLeft}s</p>
      <button onClick={handlePause}>Pause</button>
    </div>
  );
}

The interval ID needs to be remembered between renders, but it never appears on screen. Storing it in state would cause pointless re-renders. A ref is exactly right.

useRef vs useState

Aspect

useState

useRef

Triggers a re-render on changeYesNo
Value survives re-rendersYesYes
Read the valuevalueref.current
Use it forAnything shown on screenDOM nodes, timer IDs, previous values

The deciding question: does the screen need to update when this value changes? Yes → state. No → ref.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details