Skip to content

QuizNot attempted

Latest value via ref in an interval

Click the button twice within the first two seconds. What does the interval log show — stale values or up-to-date values?
function App() {
const [count, setCount] = useState(0);
const ref = useRef(count);
ref.current = count;
useEffect(() => {
const id = setInterval(() => {
console.log(ref.current);
}, 1000);
return () => clearInterval(id);
}, []);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Logs up-to-date values because ref.current is reassigned every render
  • Every render executes ref.current = count, and the interval reads ref.current (a property of a stable object) rather than a captured variable, so it logs the latest value.
  • Not 'always 0': that is what reading count directly would do.
  • Not 'throws' or undefined: the ref was initialised to count.
  • Caveat: writing refs during render is discouraged under concurrent rendering
  • update the ref in an effect or use useEffectEvent (React 19.2).