DEV Community

Vitaly Obolensky
Vitaly Obolensky

Posted on

Senior React Quiz: Stale Closures or Automatic Batching? 🧠

Let's test your understanding of React 18 execution flow and closure mechanics. Take a look at this snippet:

import { useState, useEffect } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount((c) => c + 1);
      setCount(count + 1);
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return <h1>{count}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

What number will be displayed on the screen after 3 seconds?

  • A) 6
  • B) 3
  • C) 1
  • D) 0

I was reviewing a subtle state synchronization bug with a principal frontend engineer on our team, and this exact combination of stale closures inside interval hooks came up during an architecture refactoring.

Drop your choice in the comments before testing it in CodeSandbox!

Top comments (0)