React Function Component Pattern 2:用 useRef / useEffect / useCallback 封裝 callback 函數

Steven Su
萬達寵物系統發展部
1 min readApr 18, 2019

Pure Component 是 React 中常見提升效能的方式,如果傳遞 props 給 Pure Component 時有用到 propA={{…props.A}}onChange={(e) => {...}},那有用 Pure Component 跟沒用一樣,因為每次 render 都還是會產生新的物件或函數,所以 shouldComponentUpdate 會回傳 true。

但使用 arrow function 又是人之常情,我們能做的就是避免效能大幅度惡化。可以透過合使用 useRef 和 useEffect 和 useCallback 來避免 arrow function 往下擴散,造成大量 render。

此樣式適合用在大型的共用元件,大型元件裡面有小元件,父元件要傳遞 callback 下去給子元件或者父元件會 wrap callback 才傳給子元件。例如:萬用表單中的 onChange onXXX、萬用表格中的行內編輯。

--

--