A saved callback after a re-render
Click Save and increment. Wait for the button to say 1, then click Replay. Predict the console output and final first-button text.
Code Snippet
import { useRef, useState } from "react";
export default function App() {
const [n, setN] = useState(0);
const saved = useRef(null);
return <>
<button onClick={() => {
saved.current = () => console.log(n);
setN(x => x + 1);
}}>Save and increment: {n}</button>
<button onClick={() => saved.current?.()}>Replay</button>
</>;
}Expected Output & Explanation
Console: 0
First button: Save and increment: 1 The ref preserves the saved function, and that function closes over n from the earlier render. The state update does not rewrite the saved closure.
Module Context & References
React · Predict the behavior Trace state queues, stale snapshots, keys, effects and refs
Personal Notes · Markdown