Skip to content

QuizNot attempted

Ref persists across renders

The button is clicked 3 times in a row. What do the three alert calls show?
function App() {
const ref = useRef(0);
function handleClick() {
ref.current++;
alert(ref.current);
}
return <button onClick={handleClick}>Click</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1, 2, 3
  • A ref is the same object for the component's lifetime, and mutating .current persists, so the clicks alert 1, 2, 3.
  • Not 1, 1, 1: that is a plain let reset on each render (here nothing even re-renders).
  • Not 0, 1, 2: the increment happens before the alert.
  • Not 'one alert': each click runs the handler.