React
useMemoizedFn 和 useEvent 的差异
https://mp.weixin.qq.com/s/-6bQKIjH6WPcfuiCFtsjng
function useMemoizedFn(fn) {
const fnRef = useRef(fn);
fnRef.current = useMemo(() => fn, [fn]);
return useCallback((...args) => {
return fnRef.current.apply(args);
}, []);
}
// (!) Approximate behavior
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);
}, []);
}
由于 useLayoutEffect 是在回溯期调用的,所以子节点的 useLayoutEffect 会先于父元素调用,所以如果子节点中需要通过 useLayoutEffect 获取 ref,此时的 ref 还没有更新,
所以需要一种时间点,在 useLayoutEffect 的回溯调用之前,能够改变 ref。
所以目前 useMemoizedFn 的方案是在 render 中更新 ref