I found this method the best, to ensure that the object is actually different. The "compareObjects" function doesn't have to nest deep in this example, because the object is restricted to only have strings as field-values (this is not checked in runtime, mind you).
Last active
May 23, 2022 11:50
-
-
Save lebbe/2aeee872a4b3e1f4fd6c80916701b29a to your computer and use it in GitHub Desktop.
Object as dependency in a useEffect
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
function someHook(object: Record<string, string>) { | |
// REST OF STATE HERE | |
const refObject = useRef(object) | |
useEffect(function() { | |
if(!compareObjects(object, refObject.current) { | |
// DO YOUR THINGS HERE | |
} | |
}, [object]) | |
// REST OF HOOK HERE | |
} | |
// A very simple comparison function, prefer a more solid one from a decent library | |
function compareObjects(a: Record<string, string>, b: Record<string, string>) { | |
const keysA = Object.keys(a) | |
const keysB = Object.keys(b) | |
return keysA.length === keysB.length && !keysA.some(key => a[key] !== b[key]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment