Code Review1 min read

React Code Review Interview: Stale Closures in useEffect

Practice identifying a stale closure and missing hook dependency in a focused React useEffect code review example.

Pairlet Team•Published: •Updated:

Code review interviews test candidate engineering maturity better than traditional algorithm puzzles. Candidates analyze realistic React pull requests containing concurrency bugs, performance bottlenecks, and hook misuse.

Bug 1: Stale Closure in useEffect Timer

JSX
// ❌ Flawed Implementation
function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1); // Stale closure over initial count (0)!
    }, 1000);
    return () => clearInterval(id);
  }, []); // Empty dependency array

  return <div>{count}</div>;
}

// ✅ Corrected Implementation
function TimerFixed() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount((prev) => prev + 1); // Functional state update
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <div>{count}</div>;
}

Practice React Code Review Live

Use this example as a custom prompt in a Pairlet interview room, or browse the available code review tasks.
Practice Relevant Coding Problems
Practice Live Coding

Conduct Live Coding Interviews in the Browser

No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.

Related Articles