ReactEasy

Difference between useRef and state?

Both persist across renders, but updating state triggers a re-render and gives the next render a new snapshot, while changing ref.current is a silent, immediate mutation that React does not track. Use state for anything that affects what is displayed, and refs for values the UI does not depend on.

Comparison

useStateuseRef
Triggers re-renderyesno
Value updatenext render (snapshot)immediately (ref.current = x)
Mutableno, replace via setteryes
Read during renderyesshould not (except lazy init)
Typical useUI dataDOM nodes, timer IDs, previous values, flags

Classic examples

  • Interval ID: store it in a ref, so starting and stopping does not re-render.
  • Latest value in a callback: a ref updated in an effect lets long-lived callbacks read fresh data. React 19.2's useEffectEvent now covers most of these cases more safely.
  • Previous prop: save it in a ref after render to compare later.
  • Click counter shown on screen: must be state; with a ref the number would never update visibly.

Common bug

Using a ref for UI data and wondering why the screen does not change, or reading a ref during render to decide output, which makes rendering impure and breaks with concurrent rendering and the React Compiler (its refs lint rule flags this).

Code example

tsx
1import { useRef, useState } from "react";
2
3export function Compare() {
4 const [stateCount, setStateCount] = useState(0);
5 const refCount = useRef(0);
6
7 return (
8 <div>
9 <button onClick={() => setStateCount((c) => c + 1)}>
10 State: {stateCount} {/* updates on screen */}
11 </button>
12
13 <button
14 onClick={() => {
15 refCount.current += 1; // changes immediately, but nothing re-renders
16 console.log("ref is now", refCount.current);
17 }}
18 >
19 Ref (check console)
20 </button>
21 </div>
22 );
23}
24
25// Typical correct ref use: remembering the previous value without re-rendering
26// const prev = useRef(value);
27// useEffect(() => { prev.current = value; }, [value]);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app