Last active
July 25, 2024 14:39
-
-
Save tanpld/f748ca4e0ee713a6542f97b86ce73783 to your computer and use it in GitHub Desktop.
useWhatChanged
This file contains hidden or 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
export function useWhatChanged(props: { [prop: string]: unknown }) { | |
// cache the last set of props | |
const prev = useRef(props); | |
useEffect(() => { | |
// check each prop to see if it has changed | |
const changed = Object.entries(props).reduce( | |
(a, [key, prop]: [string, unknown]) => { | |
if (prev.current[key] === prop) return a; | |
return { | |
...a, | |
[key]: { | |
prev: prev.current[key], | |
next: prop, | |
}, | |
}; | |
}, | |
{} as { [k: string]: any }, | |
); | |
if (Object.keys(changed).length > 0) { | |
console.group("Props That Changed"); | |
console.log(changed); | |
console.groupEnd(); | |
} | |
prev.current = props; | |
}, [props]); | |
} | |
// From: https://stackoverflow.com/users/6448060/rowan-baker-french |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To track what props changed