Skip to content

Instantly share code, notes, and snippets.

@tanpld
Last active July 25, 2024 14:39
Show Gist options
  • Save tanpld/f748ca4e0ee713a6542f97b86ce73783 to your computer and use it in GitHub Desktop.
Save tanpld/f748ca4e0ee713a6542f97b86ce73783 to your computer and use it in GitHub Desktop.
useWhatChanged
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
@tanpld
Copy link
Author

tanpld commented Jul 25, 2024

To track what props changed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment