在 React function component 中,常常需要處理 副作用 (side effects),例如:
在 class component 時代,這些通常寫在 componentDidMount
、componentDidUpdate
、componentWillUnmount
。
在 function component 中,React 提供的解法就是 useEffect
。
useEffect
是一個 Hook,讓你在 render 結束、DOM 更新完成後 執行副作用,並在需要時進行清理。
語法:
useEffect(() => {
// 副作用邏輯
return () => {
// 清理邏輯 (可選)
};
}, [dependencies]);
當我們呼叫 setState
時,React 的流程大致如下:
畫面會先更新,再執行 useEffect
。
[]
→ 只在第一次 render 後執行[state]
→ 當依賴值改變時執行useEffect
可以回傳一個 cleanup 函數:
useEffect(() => {
const handler = () => console.log("resize");
window.addEventListener("resize", handler);
return () => {
window.removeEventListener("resize", handler);
};
}, []);
useEffect
useEffect
是 React function component 中處理副作用的 Hook。
當呼叫setState
時,React 會先 re-render,然後更新 DOM,畫面繪製完成後才執行useEffect
。
這讓我們可以安全地處理 API、事件監聽或計時器,並透過 cleanup 做好清理。
如果需要在畫面繪製前就同步操作 DOM,則使用useLayoutEffect
。
useEffect
is the Hook for running side effects in function components.
When you callsetState
, React first re-renders and updates the DOM.
The browser paints the UI, and only thenuseEffect
runs.
This makes it safe for tasks like fetching data or setting up listeners.
If you need to manipulate the DOM before paint, you should useuseLayoutEffect
.
useEffect
= function component 的副作用管理器