Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 09:53
Show Gist options
  • Save freddi301/46a378c4ba99cf99135d281a3b0d2cb6 to your computer and use it in GitHub Desktop.
Save freddi301/46a378c4ba99cf99135d281a3b0d2cb6 to your computer and use it in GitHub Desktop.
useDebugPropChanges #react #hook
import { useRef } from "react";
/**
* @description used for identify changes between re-renders
* @example
* const changedProps = useChanges(props)
* @example
* useChanges(props, changes => console.log(changes))
*/
export function useDebugPropsChanges<T extends Record<any, any>>(
stuff: T,
sideEffect?: (changes: (keyof T)[]) => void,
): (keyof T)[] {
const ref = useRef(stuff);
if (ref.current !== stuff) {
const changes = [];
for (const k in stuff) {
if (!Object.is(stuff[k], ref.current[k])) {
changes.push(k);
}
}
ref.current = stuff;
if (sideEffect) {
sideEffect(changes);
}
return changes;
} else {
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment