以下内容为个人方便记忆使用。
1. Hook使用规则
- 只能在函数的最外层调用Hook,不能在循环、条件判断或子函数中调用。
- 只能在React函数组件或自定义Hook中调用Hook,不可在其他JavaScript函数中使用。
- 组件内使用useState、useReducer、useContext等Hook发生变化而引起重新渲染不受memo影响。
- 用useCallback不搭配memo不能阻止重复渲染。
2. useContext导致的不必要渲染
参考:# 如何有效减少使用useContext导致的不必要渲染
- 拆分 Context
- memo、useMemo 添加依赖
- 更换数据存储方式(sessionStorage),使用事件驱动替代数据驱动?
export const _setItem = function (key, newVal) {
if (key === 'height' || key === 'weight') {
var newStorageEvent = document.createEvent('StorageEvent');
const storage = {
setItem: function (k, val) {
sessionStorage.setItem(k, val);
newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
window.dispatchEvent(newStorageEvent)
}
}
return storage.setItem(key, newVal);
}
}
- 将需要 Context数据的组件拆分出,单独使用 useContext