在 React 中,为什么 useEffect 的依赖数组为空([])时,其回调函数只在组件挂载时执行一次,而不会在后续更新中触发?
Author: 图恩Category: 编程开发Views: 116Published: 2025-10-31 **Why does useEffect's dependency array being empty ([] ) trigger the callback function only once during component mount and not during subsequent updates?**
**Answer:**
When the dependency array of useEffect is empty ([]), React assumes the effect is independent of any component state or props. As a result, the effect is executed only once during component mount and its cleanup function (if present) is executed during unmount. Subsequent re-renders do not trigger the effect because React compares the dependency array's values again. Since the empty array has no comparable elements, it is treated as "no change."
**Explanation:**
The useEffect mechanism performs a shallow comparison of the dependency array. If the array is empty, React records it as "empty" during the first render. During subsequent renders, it rechecks the array and determines that no changes have occurred (the array remains empty), thus skipping the effect's execution. This behavior is commonly used to simulate the componentDidMount lifecycle in class components.
**Notes:**
- **Closure issues**: If an effect uses variables from the component scope (e.g., state, props, or functions) without adding them to the dependency array, it may cause closure issues (using the initial value instead of the latest one).
- **Use empty array correctly**: If the effect only needs to run once during mount and is not dependent on any reactive values, using an empty dependency array is appropriate.
- **Avoid missing dependencies**: The ESLint rule `react-hooks/exhaustive-deps` helps prevent missing dependencies by enforcing that all used variables are included in the dependency array.