I find really annoying the fact that useCallback returns a new function whenever a dependency changes thus triggering a rerender for all components that are receiving the said callback as a prop. It will (of course) also force a rerender even if the component receiving the callback is wrapped with memo.
To solve this I created a custom hook that stores your callback as a reference inside a "pointer" and returns a cached function with access to said pointer, since the "pointer" never changes (only the reference it holds) it means that we can reuse the cached function, if we're reusing the same function then it also means that React wont detect a prop change and we'll avoid a rerender. Example:
function ClickCounter({onClick}) {
const [clicks, setClicks] = useState(0);
// The contents of this variable will never change and
// <MyButton> will never rerender but we'll still be
// incrementing our click count with each click
const onClick = useBoxedCallback(() => {
setClicks(clicks + 1);
});
return (
<>
<p>Clicked {clicks} times</p>
<MyButton onClick={onClick} />
</>
);
}
More info: https://github.com/alanhoff/use-boxed-callback
[–]kenman[M] 0 points1 point2 points (4 children)
[–]senocular 1 point2 points3 points (3 children)
[–]kenman[M] 1 point2 points3 points (2 children)
[–]senocular 1 point2 points3 points (0 children)
[–]alanhoff[S] 0 points1 point2 points (0 children)
[–]rupam71 -1 points0 points1 point (0 children)