This hook
takes a function that created by using useCallback
(which will update every time its dependencies do) and returns a function that calls the updated callback while not updating itself. While in some cases you might care when a callback is updated, in some others (like event handlers) you likely don't. Also, when passed to a memoized child that doesn't care when the callback updates, you can save an unnecessary render, as demonstrated in this here demo.
import {useRef, useEffect, useCallback} from "react";
export default function useDecoupledCallback(callback) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
return useCallback((...args) =>
callbackRef.current(...args), [callbackRef]);
}
Does React remove the old event listeners and replace them every time their dependencies change, or does it do something like what this hook does internally? And if not, is React so fast that it doesn't make a difference?
Assuming that it doesn't make a difference in performance, can this method be safely used to shorten the dependency array of dependant hooks?
Thank you.