Last active
March 29, 2020 23:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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