本文是譯文,原文地址是:https://medium.com/@sdolidze/the-iceberg-of-react-hooks-af0b588f43fb
React Hooks 與類組件不同,它提供了用於優化和組合應用程式的簡單方式,並且使用了最少的樣板文件。
如果沒有深入的知識,由於微妙的 bug 和抽象層漏洞,可能會出現性能問題,代碼複雜性也會增加。
我已經創建了 12 個案例研究來演示常見的問題以及解決它們的方法。 我還編寫了 React Hooks Radar 和 React Hooks Checklist,來推薦和快速參考。
案例研究: 實現 Interval目標是實現計數器,從 0 開始,每 500 毫秒增加一次。 應提供三個控制按鈕: 啟動、停止和清除。
Level 0:Hello Worldexport default function Level00() {
console.log('renderLevel00');
const [count, setCount] = useState(0);
return (
<div>
count => {count}
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</div>
);
}這是一個簡單的、正確實現的計數器,用戶單擊時計數器的增加或減少。
Level 1:setIntervalexport default function Level01() {
console.log('renderLevel01');
const [count, setCount] = useState(0);
setInterval(() => {
setCount(count + 1);
}, 500);
return <div>count => {count}</div>;
}此代碼的目的是每 500 毫秒增加計數器。 這段代碼存在巨大的內存洩漏並且實現不正確。 它很容易讓瀏覽器標籤崩潰。 由於 Level01 函數在每次渲染發生時被調用,所以每次觸發渲染時這個組件都會創建新的 interval。
突變、訂閱、計時器、日誌記錄和其他副作用不允許出現在函數組件的主體中(稱為 React 的 render 階段)。 這樣做會導致用戶界面中的錯誤和不一致。
Hooks API Reference[1]: useEffect[2]
Level 2:useEffectexport default function Level02() {
console.log('renderLevel02');
const [count, setCount] = useState(0);
useEffect(() => {
setInterval(() => {
setCount(count + 1);
}, 500);
});
return <div>Level 2: count => {count}</div>;
}大多數副作用放在 useEffect 內部。 但是此代碼還有巨大的資源洩漏,並且實現不正確。 useEffect 的默認行為是在每次渲染後運行,所以每次計數更改都會創建新的 Interval。
Hooks API Reference[3]: useEffect[4], Timing of Effects[5].
Level 3: 只運行一次export default function Level03() {
console.log('renderLevel03');
const [count, setCount] = useState(0);
useEffect(() => {
setInterval(() => {
setCount(count + 1);
}, 300);
}, []);
return <div>count => {count}</div>;
}將 [] 作為 useEffect 的第二個參數,將在 mount 之後只調用一次 function,即使只調用一次 setInterval,這段代碼的實現也是不正確的。
雖然 count 會從 0 增加到 1,但是不會再增加,只會保持成 1。 因為箭頭函數隻被創建一次,所以箭頭函數裡面的 count 會一直為 0.
這段代碼也存在微妙的資源洩漏。 即使在組件卸載之後,仍將調用 setCount。
Hooks API Reference[6]: useEffect[7], Conditionally firing an effect[8].
Level 4:清理useEffect(() => {
const interval = setInterval(() => {
setCount(count + 1);
}, 300);
return () => clearInterval(interval);
}, []);為了防止資源洩漏,Hooks 的生命周期結束時,必須清理所有內容。 在這種情況下,組件卸載後將調用返回的函數。
這段代碼沒有資源洩漏,但是實現不正確,就像之前的代碼一樣。
Hooks API Reference[9]: Cleaning up an effect[10].
Level 5:使用 count 作為依賴項useEffect(() => {
const interval = setInterval(() => {
setCount(count + 1);
}, 500);
return () => clearInterval(interval);
}, [count]);給 useEffect 提供依賴數組會改變它的生命周期。 在這個例子中,useEffect 在 mount 之後會被調用一次,並且每次 count 都會改變。 清理函數將在每次 count 更改時被調用以釋放前面的資源。
這段代碼工作正常,沒有任何錯誤,但是還是有點不好,每 500 毫秒創建和釋放 setInterval, 每個 setInterval 總是調用一次。
Hooks API Reference[11]: useEffect[12], Conditionally firing an effect[13].
Level 6:setTimeoutuseEffect(() => {
const timeout = setTimeout(() => {
setCount(count + 1);
}, 500);
return () => clearTimeout(timeout);
}, [count]);這段代碼和上面的代碼可以正常工作。 因為 useEffect 是在每次 count 更改時調用的,所以使用 setTimeout 與調用 setInterval 具有相同的效果。
這個例子效率很低,每次渲染發生時都會創建新的 setTimeout,React 有一個更好的方式來解決問題。
Level 7:useState 的函數更新useEffect(() => {
const interval = setInterval(() => {
setCount(c => c + 1);
}, 500);
return () => clearInterval(interval);
}, []);在前面的例子中,我們對每次 count 更改運行 useEffect,這是必要的,因為我們需要始終保持最新的當前值。
useState 提供 API 來更新以前的狀態,而不用捕獲當前值。 要做到這一點,我們需要做的就是向 setState 提供 lambda(匿名函數)。
這段代碼工作正常,效率更高。 在組件的生命周期中,我們使用單個 setInterval, clearInterval 只會在卸載組件之後調用一次。
Hooks API Reference[14]: useState[15], Functional updates[16].
Level 8:局部變量export default function Level08() {
console.log('renderLevel08');
const [count, setCount] = useState(0);
let interval = null;
const start = () => {
interval = setInterval(() => {
setCount(c => c + 1);
}, 500);
};
const stop = () => {
clearInterval(interval);
};
return (
<div>
count => {count}
<button onClick={start}>start</button>
<button onClick={stop}>stop</button>
</div>
);
}我們增加了 start 和 stop 按鈕。 此代碼實現不正確,因為 stop 按鈕不工作。 因為在每次渲染期間都會創建新的引用(指 interval 的引用),因此 stop 函數裡面 clearInterval 裡面的 interval 是 null。
Hooks API Reference[17]: Is there something like instance variables?[18]
Level 9:useRefexport default function Level09() {
console.log('renderLevel09');
const [count, setCount] = useState(0);
const intervalRef = useRef(null);
const start = () => {
intervalRef.current = setInterval(() => {
setCount(c => c + 1);
}, 500);
};
const stop = () => {
clearInterval(intervalRef.current);
};
return (
<div>
count => {count}
<button onClick={start}>start</button>
<button onClick={stop}>stop</button>
</div>
);
}如果需要變量,useRef 是首選的 Hook。 與局部變量不同,React 確保在每次渲染期間返回相同的引用。
這個代碼看起來是正確的,但是有一個微妙的錯誤。 如果 start 被多次調用,那麼 setInterval 將被多次調用,從而觸發資源洩漏。
Hooks API Reference[19]: useRef[20]
Level 10: 判空處理export default function Level10() {
console.log('renderLevel10');
const [count, setCount] = useState(0);
const intervalRef = useRef(null);
const start = () => {
if (intervalRef.current !== null) {
return;
}
intervalRef.current = setInterval(() => {
setCount(c => c + 1);
}, 500);
};
const stop = () => {
if (intervalRef.current === null) {
return;
}
clearInterval(intervalRef.current);
intervalRef.current = null;
};
return (
<div>
count => {count}
<button onClick={start}>start</button>
<button onClick={stop}>stop</button>
</div>
);
}為了避免資源洩漏,如果 interval 已經啟動,我們只需忽略調用。 儘管調用 clearInterval (null) 不會觸發任何錯誤,但是只釋放一次資源仍然是一個很好的實踐。
此代碼沒有資源洩漏,實現正確,但可能存在性能問題。
memoization 是 React 中主要的性能優化工具。 React.memo 進行淺比較,如果引用相同,則跳過 render 階段。
如果 start 函數 和 stop 函數被傳遞給一個 memoized 組件,整個優化就會失敗,因為在每次渲染之後都會返回新的引用。
React Hooks: Memoization[21]
Level 11: useCallbackconst intervalRef = useRef(null);
const start = useCallback(() => {
if (intervalRef.current !== null) {
return;
}
intervalRef.current = setInterval(() => {
setCount(c => c + 1);
}, 500);
}, []);
const stop = useCallback(() => {
if (intervalRef.current === null) {
return;
}
clearInterval(intervalRef.current);
intervalRef.current = null;
}, []);
return (
<div>
count => {count}
<button onClick={start}>start</button>
<button onClick={stop}>stop</button>
</div>
);
}為了使 React.memo 能夠正常工作,我們需要做的就是使用 useCallback 來記憶(memoize)函數。 這樣,每次渲染後都會提供相同的函數引用。
此代碼沒有資源洩漏,實現正確,沒有性能問題,但代碼相當複雜,即使對於簡單的計數器也是如此。
Hooks API Reference[22]: useCallback[23]
Level 12: 自定義 Hookfunction useCounter(initialValue, ms) {
const [count, setCount] = useState(initialValue);
const intervalRef = useRef(null);
const start = useCallback(() => {
if (intervalRef.current !== null) {
return;
}
intervalRef.current = setInterval(() => {
setCount(c => c + 1);
}, ms);
}, []);
const stop = useCallback(() => {
if (intervalRef.current === null) {
return;
}
clearInterval(intervalRef.current);
intervalRef.current = null;
}, []);
const reset = useCallback(() => {
setCount(0);
}, []);
return { count, start, stop, reset };
}為了簡化代碼,我們需要將所有複雜性封裝在 useCounter 自定義鉤子中,並暴露 api: { count,start,stop,reset }。
export default function Level12() {
console.log('renderLevel12');
const { count, start, stop, reset } = useCounter(0, 500);
return (
<div>
count => {count}
<button onClick={start}>start</button>
<button onClick={stop}>stop</button>
<button onClick={reset}>reset</button>
</div>
);
}Hooks API Reference[24]: Using a Custom Hook[25]
React Hooks Radar✅ Green綠色 hooks 是現代 React 應用程式的主要構件。 它們幾乎在任何地方都可以安全地使用,而不需要太多的思考
🌕 Yellow黃色 hooks 通過使用記憶(memoize)提供了有用的性能優化。 管理生命周期和輸入應該謹慎地進行。
🔴 Red紅色 hooks 與易變的世界相互作用,使用副作用。 它們是最強大的,應該極其謹慎地使用。 自定義 hooks 被推薦用於所有重要用途的情況。
用好 React Hooks 的清單服從Rules of Hooks 鉤子的規則[26].Prefer 更喜歡useReducer or functional updates for 或功能更新useStateto prevent reading and writing same value in a hook. 防止在鉤子上讀寫相同的數值不要在渲染函數中使用可變變量,而應該使用useRef如果你保存在useRef 的值的生命周期小於組件本身,在處理資源時不要忘記取消設置值在需要的時候使用 Memoize 函數和對象來提高性能正確捕獲輸入依賴項(undefined=> 每一次渲染,[a, b] => 當a or 或b改變的時候渲染, 改變,[] => 只改變一次)對於複雜的用例可以通過自定義 Hooks 來實現。參考資料[1]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[2]useEffect: https://reactjs.org/docs/hooks-reference.html#useeffect
[3]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[4]useEffect: https://reactjs.org/docs/hooks-reference.html#useeffect
[5]Timing of Effects: https://reactjs.org/docs/hooks-reference.html#timing-of-effects
[6]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[7]useEffect: https://reactjs.org/docs/hooks-reference.html#useeffect
[8]Conditionally firing an effect: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect
[9]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[10]Cleaning up an effect: https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect
[11]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[12]useEffect: https://reactjs.org/docs/hooks-reference.html#useeffect
[13]Conditionally firing an effect: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect
[14]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[15]useState: https://reactjs.org/docs/hooks-reference.html#usestate
[16]Functional updates: https://reactjs.org/docs/hooks-reference.html#functional-updates
[17]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[18]Is there something like instance variables?: https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
[19]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[20]useRef: https://reactjs.org/docs/hooks-reference.html#useref
[21]React Hooks: Memoization: https://medium.com/@sdolidze/react-hooks-memoization-99a9a91c8853
[22]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[23]useCallback: https://reactjs.org/docs/hooks-reference.html#usecallback
[24]Hooks API Reference: https://reactjs.org/docs/hooks-reference.html
[25]Using a Custom Hook: https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook
[26]Rules of Hooks 鉤子的規則: https://reactjs.org/docs/hooks-rules.html