react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

Bad Example for "Examples of wrapping Effects in custom Hooks"

Open SangJunBak opened this issue 2 years ago • 2 comments

In example 2 of 3 of Wrapping Effects in Custom Hooks, the useEffect is called per render and isn't the same as before.

Screenshot 2023-04-23 at 9 01 01 PM

SangJunBak avatar Apr 24 '23 01:04 SangJunBak

Yeah i think the fix would be to wrap useWindowListener with React.memo() to avoid re-rendering on passing same props

ManavChaudhary999 avatar Apr 25 '23 12:04 ManavChaudhary999

As we're passing a new function reference every-time to the custom hook (listener argument), useEffect dependency array is getting changed and it's running on per render. one solution is to wrap the listener in App.js with useCallback.

const handlePointerMove = useCallback(e => setPosition({ x: e.clientX, y: e.clientY }), []);
useWindowListener('pointermove', handlePointerMove);

kprakhar avatar Dec 09 '23 07:12 kprakhar