Created
March 19, 2021 18:33
-
-
Save mcalthrop/034c073ed24bc421adafbaea52d670ac to your computer and use it in GitHub Desktop.
TypeScript adaptation of https://usehooks.com/useWhyDidYouUpdate/
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 React from 'react'; | |
interface FromTo { | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
from: any; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
to: any; | |
} | |
type Changes = Record<string, FromTo>; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
type GenericProps = Record<string, any>; | |
// TypeScript adaptation of https://usehooks.com/useWhyDidYouUpdate/ | |
function useWhyDidYouUpdate(name: string, props: GenericProps): void { | |
// Get a mutable ref object where we can store props ... | |
// ... for comparison next time this hook runs. | |
const previousProps = React.useRef<GenericProps>(props); | |
React.useEffect(() => { | |
if (previousProps && previousProps.current) { | |
// Get all keys from previous and current props | |
const allKeys = Object.keys({ ...previousProps.current, ...props }); | |
// Use this object to keep track of changed props | |
const changes: Changes = {}; | |
// Iterate through keys | |
allKeys.forEach((key) => { | |
// If previous is different from current | |
if (previousProps.current[key] !== props[key]) { | |
// Add to changesObj | |
changes[key] = { | |
from: previousProps.current[key], | |
to: props[key], | |
}; | |
} | |
}); | |
if (Object.keys(changes).length) { | |
console.log('[why-did-you-update]', name, changes); | |
} | |
} | |
// Finally update previousProps with current props for next hook call | |
previousProps.current = props; | |
}); | |
} | |
export default useWhyDidYouUpdate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment