SkillPilotAI

useRef

useRef gives a component a value that survives between renders without causing a re-render. It is used for things like timer ids and for direct access to DOM elements (focus, scroll, measure), and in React 19 a ref can be passed as a normal prop.

34.1 The problem: Stop does not work

  • Stopwatch keeps time in state and the interval id in a normal variable timerId.
  • start() calls setInterval and stores the id in timerId; stop() calls clearInterval(timerId).
  • Press Start, then Stop after 3 seconds: the timer keeps going to 4 and 5.
React (JSX)
function Stopwatch() {  const [time, setTime] = useState(0);  let timerId;   function start() {    timerId = setInterval(() => {      setTime((t) => t + 1);    }, 1000);  }  function stop() {    clearInterval(timerId);  }  // return: Time, Start and Stop buttons}
Output
Time: 0s-- Start, then Stop after 3s --Time: 3s-- timer keeps going --Time: 5s

34.2 Why didn't the timer stop?

  • Every second setTime changes state, so the component re-renders and the whole function runs again.
  • In the new render let timerId is declared again and is undefined: the old id is lost.
  • The Stop button uses the latest render's function, which clears undefined while the real interval keeps running.
Why a normal variable loses the timer id
  1. 1.Start: timerId = setInterval(...) in render #1

  2. 2.setTime(1): state changes

  3. 3.Re-render #2: let timerId runs again -> undefined

  4. 4.Stop click: clearInterval(undefined)

  5. 5.Real interval keeps running: 4s, 5s...

We need a value that survives between renders

34.3 Fix: useRef

  • Import useRef from React like useState; useRef(null) returns an object whose current property holds the value.
  • start() stores the interval id in timerRef.current; stop() clears that same id.
  • Stop after 3 seconds now stops at 3, because the ref keeps the same id across re-renders.
React (JSX)
function Stopwatch() {  const [time, setTime] = useState(0);  const timerRef = useRef(null);   function start() {    timerRef.current = setInterval(() => {      setTime((t) => t + 1);    }, 1000);  }  function stop() {    clearInterval(timerRef.current);  }  // return: Time, Start and Stop buttons}
Output
Time: 0s-- Start, then Stop after 3s --Time: 3s

34.4 How a ref works

  • useRef returns a plain object { current: ... }: a box where you can keep anything.
  • React returns the very same object on every render, so the value is preserved.
  • Changing current does not trigger a re-render: a ref is memory that never touches the screen.
Life of a ref
  1. 1.useRef(null) on first render -> { current: null }

  2. 2.Handler sets timerRef.current = id

  3. 3.Re-render: React returns the same object

  4. 4.current still holds id (no re-render caused)

  5. 5.Stop reads timerRef.current and clears it

Ref = remembered between renders, no re-render

34.5 DOM access: focus an input

  • Create inputRef and pass it to the input's ref prop; React puts the DOM element in inputRef.current.
  • handleClick calls inputRef.current.focus() and the cursor lands in the input.
  • Use refs for jobs React has no prop for: focus, scroll, measuring an element.
React (JSX)
function SearchBox() {  const inputRef = useRef(null);   function handleClick() {    inputRef.current.focus();  }  return (    <div>      <input ref={inputRef} />      <button onClick={handleClick}>        Focus search      </button>    </div>  );}
Output
Input: empty-- click Focus search --Input: focused, cursor blinking

34.6 React 19: ref as a prop

  • SearchInput takes ref out of its props and attaches it to the inner input.
  • Header passes its inputRef to SearchInput; clicking Search focuses the input.
  • Earlier this needed forwardRef; in React 19 it is no longer needed.
React (JSX)
function SearchInput({ ref, ...props }) {  return <input ref={ref} {...props} />;} function Header() {  const inputRef = useRef(null);  const focus = () => inputRef.current.focus();   return (    <div>      <SearchInput ref={inputRef} />      <button onClick={focus}>Search</button>    </div>  );}
Output
Input: empty-- click Search --Input: focused, cursor blinking

34.7 Comparison: variable vs state vs ref

PointNormal variableStateRef
Survives re-render?No, resets every renderYesYes
Change causes re-render?NoYesNo
Use forTemporary values in one renderData shown on screenTimer id, DOM element, flags
How to changeAssignSetter (setX)ref.current = value

34.8 Checkpoint: a ref does not update the UI

  • LikeButton keeps likes in a ref and adds 1 on every click.
  • After 3 clicks the console shows 1, 2, 3 but the button still shows Likes: 0, because changing a ref never re-renders.
  • Any value that appears in the UI must live in state.
React (JSX)
function LikeButton() {  const likesRef = useRef(0);   function handleClick() {    likesRef.current = likesRef.current + 1;    console.log(likesRef.current);  }   return (    <button onClick={handleClick}>      Likes: {likesRef.current}    </button>  );}
Output
-- after 3 clicks --[button] Likes: 0Console: 1, 2, 3

34.9 Common mistakes

  • Using a DOM ref during render: in the first render the input does not exist yet, current is null and the app crashes with a TypeError.
  • Fix: call focus inside useEffect, which runs after the DOM is ready.
React (JSX)
// Wrong: TypeError, current is null during the first renderfunction SearchBox() {  const inputRef = useRef(null);  inputRef.current.focus();  return <input ref={inputRef} />;}
React (JSX)
// Right: focused when the page opensfunction SearchBox() {  const inputRef = useRef(null);  useEffect(() => {    inputRef.current.focus();  }, []);  return <input ref={inputRef} />;}
  • Myth: "useRef is only for the DOM". Any value works: timer id, previous value, a flag not shown on screen.
  • Myth: "changing a ref updates the UI". It does not (see the checkpoint).

34.10 Rules for refs

  • Do not read or write ref.current during rendering; use it in event handlers or effects.
  • Data shown on the screen always belongs in state, not in a ref.
  • Refs are an escape hatch: do not overuse them to change the DOM directly; use the normal React way where it works.

34.11 Interview tips

  • useRef and useState both preserve a value between renders.
  • Updating state re-renders the component; changing ref.current does not.
  • State for UI data; ref for a timer id or a DOM element.
  • In React 19 a ref can be passed as a normal prop, so forwardRef is not needed.