Skip to content

QuizNot attempted

Plain variable vs ref with no re-render

Click the button 3 times. What logs each time (assume no re-render is triggered by anything else)?
function App() {
let count = 0;
const countRef = useRef(count);
const handleClick = () => {
count += 1;
console.log('local var:', count, 'ref:', countRef.current);
};
return <button onClick={handleClick}>click</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • local var: 1, ref: 0, local var: 2, ref: 0, local var: 3, ref: 0
  • Nothing triggers a re-render, so the same handleClick closure (and the same count variable) is reused and increments 1, 2, 3, while countRef.current was initialised to 0 and is never written.
  • Not 1 all three times: that would need a re-render that recreates count = 0.
  • Not ref 1, 2, 3: the handler only changes the local variable.
  • Not 'throws': count is a let, reassignment is fine.
  • (After any real re-render, the local count would reset to 0.)