使用‘useEffect’和‘useCallback’是冗余吗?
独自一人,与世隔绝?没关系,您请.这两个挂钩的存在是为了服务于两个完全不同的目的.
useEffect
个
The useEffect
个 hook is to issue intentional side-effects from what is otherwise considered to be a pure function that renders UI from JSX.
useCallback
个
The useCallback
个 hook memoizes a function such that a stable function reference is passed along, e.g. to a useEffect
个 hook, or to children as props, so it doesn't trigger unnecessary rerenders. In other words, it is a performance optimization/optimizer.
Instead of recreating the handleBackPress
and adding/removing event listeners each time the onBackEvent
is changed, I recommend moving handleBackPress
into the useEffect
个 hook so it can be provided as a stable callback reference, and to use a React ref to cache the onBackEvent
callback. Use an empty array for the useEffect
个 hook so the listeners are only instantiated once and removed when the component unmounts via the cleanup function.
示例:
export default function useIndex(onBackEvent?: () => void) {
const onBackEventRef = React.useRef<() => void | undefined>();
useEffect(() => {
onBackEventRef.current = onBackEvent;
}, [onBackEvent]);
useEffect( () => {
const handleBackPress = (e: PopStateEvent) => {
e.preventDefault();
window.history.pushState(null, '', window.location.pathname);
if (onBackEventRef.current) {
onBackEventRef.current();
}
};
window.history.pushState(null, '', window.location.pathname);
window.addEventListener('popstate', handleBackPress);
return () => {
window.removeEventListener('popstate', handleBackPress);
};
}, []);
}