I don't understand why useCallback
always returns a new ref each time one of the deps is updated. It results in many re-render that React.memo()
could have avoided.
What is, if any, the problem with this implementation of useCallback
?
export function useCallback(callback) {
const callbackRef = useRef();
callbackRef.current = callback;
return useState(() =>
(...args) => callbackRef.current(...args)
)[0];
}
Using this instead of the built-in implementation sure has a significant positive impact on performance.
Own conclusion:
There is no reason not to use an implementation using ref over the built's in as long as you are aware of the implications, namely, as pointed out by @Bergy, you can't store a callback for use later (after a setTimeout
for example) and expect the callback to have the same effect as if you'd have called it synchronously.
In my opinion however this is the preferred behaviour so no downside .
Update:
There is a React RFC for introducing a builtin hook that does just that. It would be called useEvent