File size: 1,385 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import { useEffect, useRef } from 'react';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function useWhyDidYouUpdate(name: string, props: any) {
// Get a mutable ref object where we can store props ...
// ... for comparison next time this hook runs.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const previousProps = useRef<any>();
useEffect(() => {
if (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 changesObj: Record<string, unknown> = {};
// Iterate through keys
allKeys.forEach((key) => {
// If previous is different from current
if (previousProps.current[key] !== props[key]) {
// Add to changesObj
changesObj[key] = {
from: previousProps.current[key],
to: props[key],
};
}
});
// If changesObj not empty then output to console
if (Object.keys(changesObj).length) {
// tslint:disable-next-line:no-console
console.log('[why-did-you-update]', name, changesObj);
}
}
// Finally update previousProps with current props for next hook call
previousProps.current = props;
});
}
export default useWhyDidYouUpdate;
|