Last active
April 1, 2023 19:02
-
-
Save hekystyle/e5614528d41f7d4f3bd78cc521f2f697 to your computer and use it in GitHub Desktop.
usePropsComparison
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
| 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