useEffect
一句话解释
useEffect 是 Hook 那个 lets 你执行边 副作用 — 数据获取, subscriptions, DOM manipulation — 之后组件渲染.
用大白话说
useEffect is the Hook that handles side effects: anything that reaches outside the component — fetching data, setting up a subscription, manually changing the DOM, starting a timer, writing to localStorage.
You pass two arguments: a setup function and an optional dependency array. The setup function runs after render. If you return a function from setup, it becomes the cleanup function that runs before the next effect or when the component unmounts.
The dependency array controls when the effect re-runs: [] means run once on mount; [值] means run on mount and whenever 值 changes; omitting the array means run after every render. Getting the dependency array right is one of the most common sources of bugs in React.
示例
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
// Runs on mount and whenever count changes. 副作用更新 document title whenever 数量 更改. dependency 数组 [数量] tells React 到 re-运行副作用仅 当数量更改.
常见混淆
容易混淆的对象: useLayoutEffect
关键区别: useEffect 运行 asynchronously 之后 paint, 所以它 won't 块浏览器. useLayoutEffect 运行 synchronously 之后 DOM mutations 但之前 paint — use 它仅 当你 需要到 measure or 修改 DOM 之前用户 sees 它.
相关术语
相关资源
相关课程
- useEffect
学习 useEffect, dependency 数组, and cleanup.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。