Skip to content

QuizNot attempted

Previous value with a ref

After clicking + twice (count now 2), what does the <p> show?
function App() {
const [count, setCount] = useState(0);
const prevCount = useRef();
useEffect(() => {
prevCount.current = count;
});
return (
<div>
<p>Now: {count}, Before: {prevCount.current}</p>
<button onClick={() => setCount(c => c + 1)}>+</button>
</div>
);
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Now: 2, Before: 1
  • Effects run after render, so each render displays prevCount.current from the previous render's effect, one step behind: at count = 2 it shows Before: 1.
  • Not Before: 2: the effect writing 2 runs after this render is painted.
  • Not Before: 0: the effect after the count = 1 render already stored 1.
  • Not undefined: only the very first render shows undefined.