在 React 中,为什么使用 useEffect 时依赖数组为空会导致 effect 只在组件挂载和卸载时执行一次?

**Why does an empty dependency array in React's useEffect cause the effect to execute only once during component mount and unmount?** **Answer and Explanation:** When the dependency array (second parameter) of useEffect is an empty array [], React treats the effect as independent of any external variables or changes to props/state. As a result, the effect is executed only once during the component's initial mount and once during its unmount. **Principle:** The useEffect mechanism works by re-evaluating the effect after each component render. If the dependency array is empty, React assumes there's nothing to change, thus preventing the effect from executing again in subsequent renders. **Example:** ```jsx useEffect(() => { console.log('Component mounted'); return () => { console.log('Component will unmount'); }; }, []); // Empty dependency array ``` The `console.log('Component mounted')` is executed only once during the component's first render. When the component is removed, the cleanup function is executed once. **Notes:** If an effect uses certain state or props but does not include them in the dependency array, it leads to a closure trap (stale closure), where the effect references the initial value rather than the latest value. To avoid this, ensure the dependency array fully reflects the reactive variables used in the effect, or use ESLint's `react-hooks/exhaustive-deps` rule to prevent missed dependencies.