useState vs useRef — When to Use Each in React
The Interview Question
What are the differences between useState and useRef? When would you choose one over the other?
Expert Answer
useState and useRef both persist values across renders, but they serve fundamentally different purposes. useState triggers a re-render when its value changes — it's for data that the UI depends on. useRef holds a mutable value that persists across renders without causing re-renders. Think of useRef as a container whose .current property you can read and write freely without React knowing or caring. The most common use of useRef is holding DOM element references, but it's also perfect for storing previous values, timer IDs, or any mutable value that shouldn't trigger a re-render when it changes.
Key Points to Hit in Your Answer
- useState causes re-renders; useRef does not
- useRef.current is mutable and can be changed directly
- useRef persists the same object reference across renders
- Common useRef patterns: DOM access, storing previous props/state, holding timer/interval IDs, tracking whether a component is mounted
Code Example
// useState — triggers re-render, updates the UI
const [count, setCount] = useState(0);
// useRef — does NOT trigger re-render
const renderCount = useRef(0);
useEffect(() => {
renderCount.current += 1;
// This doesn't cause another render
});
// useRef for DOM access
const inputRef = useRef(null);
const focusInput = () => inputRef.current.focus();
What Interviewers Are Really Looking For
Interviewers want you to articulate the re-render distinction clearly. A strong answer includes a real-world scenario where using useState would cause unnecessary renders and useRef is the better choice — like tracking a timer ID or storing a previous value for comparison.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →