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
useState | useRef | |
|---|---|---|
| Triggers re-render | yes | no |
| Value update | next render (snapshot) | immediately (ref.current = x) |
| Mutable | no, replace via setter | yes |
| Read during render | yes | should not (except lazy init) |
| Typical use | UI data | DOM 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
useEffectEventnow 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";23export function Compare() {4 const [stateCount, setStateCount] = useState(0);5 const refCount = useRef(0);67 return (8 <div>9 <button onClick={() => setStateCount((c) => c + 1)}>10 State: {stateCount} {/* updates on screen */}11 </button>1213 <button14 onClick={() => {15 refCount.current += 1; // changes immediately, but nothing re-renders16 console.log("ref is now", refCount.current);17 }}18 >19 Ref (check console)20 </button>21 </div>22 );23}2425// Typical correct ref use: remembering the previous value without re-rendering26// 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.