30 seconds of code 实战:用 React useInterval 自定义 Hook 声明式封装 setInterval

原创2026-10-05 10:44:481,948 阅读
文章标签:教程文档

30 seconds of code 实战:用 React useInterval 自定义 Hook 声明式封装 setInterval

定时器逻辑与 React 渲染模型之间的摩擦,是函数组件开发中最常见的痛点之一。本文以 30 seconds of code 仓库中的 useInterval 文档 为核心,逐步拆解如何把命令式的 setInterval() 封装成声明式的自定义 Hook,并针对闭包陷阱、依赖刷新、卸载清理给出可复用的完整实现,最终交付一个可直接复制的 useInterval() 及秒表组件示例。

为什么 setInterval 在 React 中难以直接使用

Wrapping your mind around React hooks can be daunting at first, especially if you stumble into anything remotely related to timing, such as setInterval(). In order to solve such issues, you have to get used to the way hooks work, their limitations and potential workarounds.

在 React 函数组件中直接调用 setInterval() 会面临三个层面的问题:

  1. 副作用位置错误:setInterval() 不属于渲染流程,它创建的是组件之外的任务;
  2. 闭包过期:定时器回调捕获的是创建时刻的渲染闭包,拿不到最新状态;
  3. 生命周期清理:组件卸载时若未调用 clearInterval(),会留下幽灵定时器,造成内存泄漏与状态更新报错。

这正是 30 seconds of code 的 React 文章集合所要解决的问题。根据 React 集合配置 与 Hooks 集合配置 的说明,该集合面向 React 18,收录函数组件与可复用自定义 Hook,useInterval 即其中「hooks + effect」标签下的代表性条目。

把 setInterval 当作副作用:第一版实现

First, it should be clear that setInterval() is a side effect. After all, it's not directly tied to a component's render method. Therefore we should call it inside a useEffect() hook and use its return to call clearInterval() when unmounting. To avoid creating multiple intervals, we can use the hook's second argument to pass an empty dependency array ([]). This results in running the side effect only when the component mounts.

将 setInterval() 放进 useEffect() 是最基本的正确姿势:

React.useEffect(() => {
  let id = setInterval(callback, delay);
  return () => clearInterval(id);
}, []);

这里的要点:

  • useEffect() 的返回函数是清理函数,会在组件卸载时执行,保证 clearInterval(id) 必然调用;
  • 空依赖数组 [] 让副作用只在挂载时执行一次,避免重复创建多个 interval;
  • 组件卸载后,interval 被清理,不会再触发对已卸载组件的更新。

这一版解决了「副作用位置」与「生命周期清理」,但尚未解决「闭包过期」。

闭包陷阱:为什么回调拿不到新值

The closure inside setInterval() will only ever have access to whatever variables and values were available when it got instantiated. This means we have to be extra careful about its first argument to make sure that fresh values will be available every time the interval runs. The easiest solution to this issue is to create a variable that's considered mutable by React, using the useRef() hook. This will allow us to have access to new values when we need them.

setInterval() 内部形成的闭包,只能访问它被实例化那一刻可用的变量与值。也就是说,无论 interval 运行多少次,回调里看到的都是首次创建时的旧闭包。若回调依赖组件的状态或 props,就会读到过期值。

最直接的补救手段是借助 useRef()。React 将 ref 视为可变的容器,其 .current 属性可以在渲染之间自由读写,从而让 interval 回调随时取到最新值:

const savedCallback = React.useRef(callback);

React.useEffect(() => {
  let id = setInterval(savedCallback.current, delay);
  return () => clearInterval(id);
}, []);

不过,这样写只是「把问题搬了个位置」:savedCallback.current 在 effect 创建时被读入 interval,之后依然保持不变——ref 的内容不会自己刷新。

用包装函数保持 ref 永远新鲜

Using the useRef() hook might have just shifted the problem. The value of the created ref now needs to be refreshed inside setInterval(). Luckily, this is an easy problem to solve. We could create a wrapper function that passes the function to setInterval() instead. This way the function passed to setInterval() will never change, but the value of the enclosed ref will always be up to date when it's called.

既然 interval 里的函数引用一旦确定便不会改变,那就让这个「不变的函数」去间接调用「可变的 ref」:

const savedCallback = React.useRef(callback);

React.useEffect(() => {
  function tick() {
    savedCallback.current();
  }
  let id = setInterval(tick, delay);
  return () => clearInterval(id);
}, []);

这里的关键转变:

  • 传给 setInterval() 的 tick 函数引用永不改变,因此 interval 结构稳定;
  • 每次触发时,tick 内部读取 savedCallback.current,而该值只要在渲染过程中被更新,就始终指向最新回调。

唯一遗留的问题:谁在何时更新 savedCallback.current?这就引出了最终版的封装。

提取可复用的 useInterval 自定义 Hook

Finally, let's extract all of this into a custom hook to make it reusable. We can extract callback as an argument for the custom hook and use it as the sole dependency of an additional useEffect() hook that will update the ref for the callback. Moreover, let's add a delay argument to the custom hook to make it more versatile.

把以上思路提炼为自定义 Hook:callback 与 delay 作为参数,第一个 useEffect() 以 callback 为唯一依赖负责刷新 ref,第二个 useEffect() 以 delay 为依赖负责创建/销毁 interval:

const useInterval = (callback, delay) => {
  const savedCallback = React.useRef();

  React.useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  React.useEffect(() => {
    const tick = () => {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
};

逐段解读这个最终实现:

部分 职责 依赖项
useRef() 保存最新回调的可变容器 —
第一个 useEffect() 每当 callback 变化,刷新 savedCallback.current [callback]
第二个 useEffect() 创建 interval 并注册清理函数 [delay]
delay !== null 判断 传 null 时暂停定时器,不创建 interval —

设计亮点:

  1. 回调永远最新:第一个 effect 保证每次渲染后 ref 都指向当前闭包,interval 回调无论何时触发都执行最新逻辑;
  2. 定时器生命周期与 delay 绑定:delay 变化时旧的 interval 被清理、新的被创建,无需手动管理;
  3. 可暂停能力:delay 传 null 时不启动定时器,实现了声明式的暂停/恢复控制,这一点也与仓库中姊妹篇 useTimeout 钩子 的实现思路完全一致——后者用 setTimeout() 加 clearTimeout() 做了同构封装,且该文明确建议先阅读 useInterval 再学习它,可见二者共享同一套「ref 保存回调 + 包装函数 + 延迟依赖」模式。

实战:每秒递增的 Timer 组件

That's pretty much it. Now, to use it, you just need to call the useInterval() hook with a callback and a delay. Here's an example of a simple timer component that increments a counter every second:

封装完成后,用法极其简洁——调用 useInterval(callback, delay) 即可。下面是一个每秒递增计数器的 Timer 组件:

const Timer = props => {
  const [seconds, setSeconds] = React.useState(0);
  useInterval(() => {
    setSeconds(seconds + 1);
  }, 1000);

  return <p>{seconds}</p>;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <Timer />
);

运行效果与要点:

  • 组件挂载后每 1000ms 触发一次回调,seconds 自增并重渲染;
  • 得益于 ref 机制,即使回调闭包在每次渲染后都不同,interval 始终执行最新版本;
  • 组件卸载时清理函数自动执行,不会产生泄漏;
  • 若需要暂停,将 delay 改为 null 即可。

在 30 seconds of code 仓库中继续延伸

useInterval 是理解 React 定时器类 Hook 的基石,围绕它可以继续研读仓库中的相关资源:

  • useInterval 原文:本文对应的原始条目,含完整 frontmatter 与说明;
  • useTimeout 钩子:setTimeout() 的同构实现,代码结构几乎一一对应,建议对照阅读;
  • useRequestAnimationFrame 钩子:基于 requestAnimationFrame() 的高频动画实现,同样使用 ref 保存回调并在卸载时取消;
  • Hooks 集合配置 与 React 集合配置:了解整个 hooks 文章集合的组织方式与 React 18 定位;
  • Snippet 模板:仓库内每个 snippet 条目遵循的 frontmatter 规范(title、shortTitle、language、tags、cover、excerpt、dateModified 等),可据此判断条目的收录标准。

这套「副作用进 effect、ref 保存最新回调、包装函数固定引用、delay 驱动生命周期」的组合拳,不只适用于 interval,同样可以迁移到 timeout、动画帧、事件监听等一切需要与渲染无关的周期性或异步任务的场景,是 React 自定义 Hook 设计中最值得掌握的范本之一。

登录后查看全文
30-seconds-of-code