Skip to main content
React Interview Questions Predict Output P0 Hard

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.

Official Reference

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

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.