Created
October 11, 2019 09:53
-
-
Save freddi301/46a378c4ba99cf99135d281a3b0d2cb6 to your computer and use it in GitHub Desktop.
useDebugPropChanges #react #hook
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
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