Skip to content

Instantly share code, notes, and snippets.

@aholachek
Last active March 29, 2020 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aholachek/8fa6be3ca9ca5425859a1313af424c9c to your computer and use it in GitHub Desktop.
Save aholachek/8fa6be3ca9ca5425859a1313af424c9c to your computer and use it in GitHub Desktop.
For the rare times when you need to do a deep object comparison in React's useCallback
import { useRef } from "react";
import cloneDeep from "lodash.clonedeep";
import isEqual from "lodash.isequal";
const useDeepEqualCallback = (callback: any, deps: any[]) => {
const callbackRef = useRef(callback);
const cachedDeps = useRef(cloneDeep(deps));
if (!isEqual(deps, cachedDeps.current)) {
callbackRef.current = callback;
cachedDeps.current = cloneDeep(deps);
}
return callbackRef.current;
};
export default useDeepEqualCallback;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment