R
Rishtaara
React: The Complete Guide
Lesson 19 of 28Article14 min

useRef Hook

useRef returns a { current } object that persists across renders. Changing ref.current does not trigger a re-render.

useRef — DOM access and mutable values

useRef returns a { current } object that persists across renders. Changing ref.current does not trigger a re-render.

Common uses: focus an input, measure a div, store a timer ID, or keep previous prop value.

Real-life example: useRef is a sticky note on your monitor — you update it anytime without telling the whole office to refresh their screens.

Focus input with useRef
import { useRef } from "react";

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

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

  return (
    <>
      <input ref={inputRef} placeholder="Search Rishtaara" />
      <button onClick={focusInput}>Focus search</button>
    </>
  );
}

Ref vs state

Use state when UI must update. Use ref when you need to remember something without re-rendering.

Real-life example: State is the scoreboard everyone watches. Ref is your private tally marks on paper — useful, but the crowd does not need to see every mark.

Store interval ID in ref
const timerRef = useRef(null);

function startTimer() {
  timerRef.current = setInterval(() => console.log("tick"), 1000);
}

function stopTimer() {
  clearInterval(timerRef.current);
}