Why can't `useCallback` always return the same ref

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, deps) {

    const callbackRef = useRef(callback);

    useMemo(
        () => callbackRef.current = callback,
        deps
    );

    return useState(() =>
        (...args) => callbackRef.current(...args)
    )[0];

}

Using this instead of the built-in implementation sure has a significant positive impact on performance.

13 thoughts on “Why can't `useCallback` always return the same ref”

Leave a Comment