Senior React Quiz: Stale Closures or Automatic Batching? 🧠
Senior React Quiz: Stale Closures or Automatic Batching? 🧠
React 进阶测验:陈旧闭包(Stale Closures)还是自动批处理?🧠
Let’s test your understanding of React 18 execution flow and closure mechanics. Take a look at this snippet: 让我们测试一下你对 React 18 执行流程和闭包机制的理解。请看这段代码:
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>;
}
What number will be displayed on the screen after 3 seconds? A) 6 B) 3 C) 1 D) 0 3 秒后屏幕上会显示什么数字?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. 我最近正与团队的一位首席前端工程师一起排查一个微妙的状态同步 Bug,在架构重构过程中,恰好遇到了这种在 interval hook 中使用陈旧闭包的典型案例。
Drop your choice in the comments before testing it in CodeSandbox! 在去 CodeSandbox 测试之前,请在评论区留下你的答案!