Skip to content

Instantly share code, notes, and snippets.

@lebbe
Last active May 23, 2022 11:50
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 lebbe/2aeee872a4b3e1f4fd6c80916701b29a to your computer and use it in GitHub Desktop.
Save lebbe/2aeee872a4b3e1f4fd6c80916701b29a to your computer and use it in GitHub Desktop.
Object as dependency in a useEffect

When relying on an object in useEffect dependency array

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).

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