useEffect 钩子与依赖数组
了解 useEffect 的运行时机,使用依赖数组控制它,并通过返回清理函数来清理订阅或计时器。
useEffect 钩子与依赖数组 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is useEffect?
useEffect lets function components perform side effects: fetching data, setting up subscriptions, manipulating the DOM, starting timers, or calling native APIs. Side effects cannot be run directly in the render function because renders must be pure. useEffect runs after the component renders to the screen.
import { useEffect } from 'react';
function App() {
useEffect(() => {
console.log('Component rendered');
// Side effects go here
});
}The Dependency Array
The second argument to useEffect is the dependency array. React uses it to decide when to re-run the effect. If the dependency array is omitted, the effect runs after every render. If it is empty ([]), the effect runs once after the initial render. If it contains values, the effect re-runs whenever any of those values change.
// Runs after every render
useEffect(() => { ... });
// Runs once on mount
useEffect(() => { ... }, []);
// Runs on mount and whenever userId changes
useEffect(() => { ... }, [userId]);Fetching Data on Mount
The most common useEffect pattern is fetching data when a component first mounts. Pass an empty dependency array to ensure the fetch runs exactly once. Store the result in state and render it in the JSX. React calls the effect after the initial paint, so the component renders once with empty/loading state before the data arrives.
function PostsScreen() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => setPosts(data));
}, []); // empty array = run once on mount
return <FlatList data={posts} ... />;
}Reactive Dependencies
When you want the effect to re-run whenever a value changes (like a search query or a user ID), list that value in the dependency array. React compares each dependency with its previous value after every render, and if any have changed, it re-runs the effect. This creates a reactive data flow: UI event → state update → effect re-runs.
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch('/api/users/' + userId)
.then((res) => res.json())
.then((data) => setUser(data));
}, [userId]); // re-fetch whenever userId changes
if (!user) return <ActivityIndicator />;
return <Text>{user.name}</Text>;
}The Cleanup Function
Return a function from your effect to perform cleanup. React calls this cleanup function before re-running the effect (on dependency changes) and when the component unmounts. Use it to cancel subscriptions, clear timers, or abort fetch requests to prevent memory leaks and state updates on unmounted components.
useEffect(() => {
const timer = setInterval(() => {
setTime(Date.now());
}, 1000);
return () => clearInterval(timer); // cleanup on unmount or re-run
}, []);Cancelling Fetch Requests with AbortController
When a component unmounts before a fetch completes, React will warn about updating state on an unmounted component. Use the AbortController to cancel the in-flight fetch in the cleanup function. Catching the abort error (which is an AbortError) prevents it from being logged as an unexpected error.
useEffect(() => {
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => controller.abort();
}, []);Running Code Only on Unmount
To run code only when the component unmounts (like unsubscribing from an event listener), return a cleanup function from a useEffect with an empty dependency array. React calls the cleanup only when the component leaves the tree, never on subsequent renders.
useEffect(() => {
const subscription = eventEmitter.addListener('change', handler);
return () => {
subscription.remove(); // only on unmount
};
}, []); // empty array = mount-only effectMultiple useEffect Calls
You can and should use multiple useEffect calls in one component — one for each independent side effect. React runs them in the order they appear after every render. Keeping effects separated by concern makes the code easier to read and avoids complex dependency arrays that mix unrelated logic.
// Effect 1: fetch user data
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
// Effect 2: analytics page view
useEffect(() => {
analytics.logScreenView('Profile');
}, []);
// Effect 3: sync title to header
useEffect(() => {
navigation.setOptions({ title: user?.name ?? 'Profile' });
}, [user, navigation]);Dependency Pitfalls: Missing Dependencies
A common bug is omitting a dependency from the array. The effect captures a stale value of the missing dependency and runs with outdated data. Always include every value from the component scope that is read inside the effect. ESLint's react-hooks/exhaustive-deps rule catches these automatically.
// Bug: fetchUser uses userId but it is not in deps
// If userId changes, the effect still runs with the old userId
useEffect(() => {
fetchUser(userId).then(setUser);
}, []); // Missing userId!
// Correct:
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);Avoiding Infinite Loops
If your effect updates state that is also listed as a dependency, you get an infinite loop: render → effect → state update → render → effect → .... Guard against this with a condition inside the effect, or restructure so the effect does not trigger the state update that caused it to run.
// Infinite loop: effect updates 'count' which is in deps
useEffect(() => {
setCount(count + 1); // triggers re-render → effect runs again
}, [count]);
// Fix: use functional updater — no need to list count as dep
useEffect(() => {
setCount((c) => c + 1);
}, []); // only runs onceComparing Effects to Lifecycle Methods
useEffect replaces all three classic class component lifecycle methods: componentDidMount (empty deps array), componentDidUpdate (with deps), and componentWillUnmount (cleanup function). One hook handles all three phases, keeping related logic together rather than spread across three separate methods.
useEffect(() => {
// componentDidMount equivalent — fetch initial data
fetchData();
return () => {
// componentWillUnmount equivalent — cancel subscriptions
cancelSubscription();
};
}, []); // runs once on mount, cleanup on unmountQuick Check
Test your understanding of the useEffect hook and dependency arrays from this lesson.
Lesson Recap
In this lesson you learned: useEffect runs side effects after render, the dependency array controls when the effect re-runs — empty means once on mount, and return a cleanup function to cancel subscriptions, timers, and fetch requests on unmount. Next up we make GET requests with Axios inside useEffect.
常见问题解答
「useEffect 钩子与依赖数组」课时是免费的吗?
是的 — 「useEffect 钩子与依赖数组」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。
「useEffect 钩子与依赖数组」这节课中我会学到什么?
了解 useEffect 的运行时机,使用依赖数组控制它,并通过返回清理函数来清理订阅或计时器。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 React Native Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「useEffect 钩子与依赖数组」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 React Native Academy 课中编写并运行代码吗?
能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- useEffect 钩子与依赖数组
- 使用 Axios 发起 GET 请求
- 处理加载与错误状态
- 使用 Axios 发送 POST、PUT 与 DELETE 请求