静待秋风
吹拂眉梢
---------写下便是永恒
2022 年 5 月 5 日,一个新的hook提案:useEvent。
其目的是返回一个永远引用不变(always-stable)的事件处理函数
没有 useEvent 时我们如何写事件函数
const [text, setText] = useState("");
const onClick = () => {
sendMessage(text);
};
return <SendButton onClick={
onClick} />;
}
为了访问最新的 state,onClick在每次chat组件更新时,都会声明一个新的函数(引用变化)
React 比较两个组件要diff 前,会对props 进行浅比较
同时它还会破坏你的 memo 优化
const SendButton = React.memo(() => {
});
优化:
function Chat() {
const [text, setText] = useState("");
const onClick = useCallback(() => {
sendMessage(text);
}, [text]);
return <SendButton onClick={
onClick} />;
}
当text变化时,引用还是会改变,依然会带来子组件没必要的更新。。。
function Chat() {
const [text, setText] = useState("");
const onClick = useEvent(() => {
sendMessage(text);
});
return <SendButton onClick={
onClick} />;
}
onClick已经一直是引用不变的了,而且可以访问到最新的 text。
function useEvent(handler) {
const handlerRef = useRef(null);
// In a real implementation, this would run before layout effects
useLayoutEffect(() => {
handlerRef.current = handler;
});
return useCallback((...args) => {
// In a real implementation, this would throw if called during render
const fn = handlerRef.current;
return fn(...args);
}, []);
}
最核心的地方就是使用 useRef 维持最新引用以及缓存住外层的 function
不可避免的需要改动 fiber tree commit 阶段逻辑