You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
《React 思維進化》讀書會第二組 5-3
簡報
5-3 維護資料流的流動:不要欺騙 hooks 的 dependencies
概念回顧
a. 宣告式同步化
欺騙 Dependencies 會造成什麼問題?
讓 effect 函式對於依賴的資料自給自足
利用前面概念回顧的 updater function 來呼叫 setCount, 用既有的值做計算,就不用依賴 state: count 變數去做更新,可以使用相同的 setInterval 去執行需要的動作,並做到資料解耦。
函式型別的依賴
常見問題: 函式寫在 dependencies 的問題,會因為每次 re-render 都建立了一個新的函式。但若避寫了函式在 dependencies 去欺騙 React, 很可能會造成非預期性的錯誤
以 linter 來輔助填寫 dependencies
eslint-plugin-react-hooks
React 官方有提供 ESLint 插件
在 Create React App 和 Next.js 中有內建此插件
如果使用 VS Code,需安裝「ESLint」擴充功能,才會正常顯示
Effect dependencies 常見的錯誤用法
撰寫空陣列,讓 Component 只在做初次渲染時執行 effect 函式,欺騙 dependencies 來控制 effect 函式執行時機
解決方法: 若只想執行一次副作用函式,可以改以條件式判斷 + useRef 來控制商業邏輯的執行時機。
QA
setState
後的Object.is
比較只是防呆機制,就算拿掉Object.is
,整個運作還是不會壞掉useEffect
在 deps 可跳過時還是有被執行到,只是最後沒有執行 effect 函式useCallback
不會避免 fn 被建立,fn 參數傳入的函式建立後,才會傳給useCallback
useCallback
本身無法帶來效能優化,是要讓函式能正確反映資料是否變化useCallback
都會產生新函式,只是會根據依賴值決定回傳前一次的還是新的Beta Was this translation helpful? Give feedback.
All reactions