Skip to content

useEffect Hook

边副作用, dependency 数组, cleanup 函数, and avoiding 无限 re-渲染循环.

你将学到

  • 什么边 副作用是 and 为什么它们需要 useEffect
  • dependency 数组 and 当副作用 re-运行
  • Cleanup 函数 for subscriptions and timers
  • 常见 pitfalls 如 missing dependencies and 无限循环

概念讲解

What Is useEffect?

React components should be pure functions of their props and state — they should not have side effects during render. Side effects include fetching data, subscribing to events, setting timers, manually changing the DOM, and logging. The useEffect hook lets you perform these side effects after the render is committed to the screen. Think of it as React's way of saying " 组件有 rendered, 现在你能做 things 那个 affect 之外世界."

The Dependency Array

The second argument to useEffect is the dependency array. It controls when the effect re-runs. An empty array [] means the effect runs only once after the initial mount. No array at all means the effect runs after every render. An array with values [, b] means the effect runs after the initial render and whenever ` or b` changes. Getting the dependency array right is crucial — missing dependencies cause stale closures, and extra dependencies cause unnecessary re-runs.

Cleanup Functions

If your effect creates a resource that needs cleaning up — a subscription, a timer, an event listener, a WebSocket connection — you return a cleanup function from the effect. React calls this cleanup before re-running the effect and when the component unmounts. This prevents memory leaks and stale callbacks. For example, if you set up an interval, return () => clearInterval(id) to clear it.

Avoiding Infinite Loops

A common mistake is updating state inside an effect that has that same state in its dependency array, causing an infinite render loop. If you must update state in an effect, make sure the effect does not depend on the state it updates, or add a guard condition. Consider whether the logic truly belongs in an effect or if it can be computed during render or moved to an event handler.

示例代码

              import { useState, useEffect } from "react";

function WindowSize() {
  const [width, setWidth] = useState(window.innerWidth);
  const [count, setCount] = useState(0);

  // Effect with cleanup — runs on mount and unmount only.
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    // Cleanup function removes the listener.
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty deps = run once.

  // Effect that depends on count — re-runs when count changes.
  useEffect(() => {
    document.title = `Clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>Window width: {width}px</p>
      <button onClick={() => setCount(c => c + 1)}>Click count: {count}</button>
    </div>
  );
}
            

首先副作用设置上 resize 监听器使用 cleanup and 空 dependency 数组 (运行一次). 其次更新 document title whenever 数量更改.

动手试一试

  • Code Diff

    Compare 副作用 logic 之前 and 之后 fixing dependency issues.

  • JSON Formatter

    格式 API 响应数据获取内部 useEffect.

常见错误

错误写法

Forgetting 到包含 dependencies in dependency 数组

正确做法

如果你的副作用 uses prop or 状态值, 包含它 in dependency 数组. 否则, 副作用 captures stale 值. Use eslint-plugin-react-Hook exhaustive-deps 规则到 catch 这个.

错误写法

更新状态 in 副作用那个 depends on 那个相同状态

正确做法

这个 causes 无限渲染循环. 添加 guard 条件, 移除状态从 deps, or move logic 到事件处理函数. Ask whether 副作用是 truly 必要.

练习 useEffect Hook

14 个练习

练习 useEffect Hook

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误