Skip to content

Instantly share code, notes, and snippets.

@hekystyle
Last active April 1, 2023 19:02
Show Gist options
  • Select an option

  • Save hekystyle/e5614528d41f7d4f3bd78cc521f2f697 to your computer and use it in GitHub Desktop.

Select an option

Save hekystyle/e5614528d41f7d4f3bd78cc521f2f697 to your computer and use it in GitHub Desktop.
usePropsComparison
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
export const usePropsComparison = (props: Record<string, unknown>) => {
const prev = usePrevious(props);
const keys = new Set([...Object.keys(props), ...Object.keys(prev ?? {})]);
const comparison = Array.from(keys).reduce<Record<string, unknown>>(
(acc, key) => ({
...acc,
[key]: [prev?.[key], prev?.[key] === props?.[key] ? '===' : '!==', props?.[key]],
}),
{},
);
return comparison;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment