Created
April 13, 2020 03:24
-
-
Save phucdph/1c78bec2aa926a849bac7e5b8e224dd3 to your computer and use it in GitHub Desktop.
[Hook] useWhyDidUpdate
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
| const useWhyDidYouUpdate = (name: string, props: any) => { | |
| const previousProps = useRef<any>({}); | |
| useEffect(() => { | |
| if (previousProps.current) { | |
| const allKeys = Object.keys({ | |
| ...(previousProps.current || {}), | |
| ...props | |
| }); | |
| const changesObj = {} as any; | |
| allKeys.forEach(key => { | |
| if (previousProps.current[key] !== props[key]) { | |
| changesObj[key] = { | |
| from: (previousProps.current || {})[key], | |
| to: props[key] | |
| }; | |
| } | |
| }); | |
| if (Object.keys(changesObj).length) { | |
| console.groupCollapsed(`${name} updated:`); | |
| for (const key in changesObj) { | |
| // eslint-disable-next-line no-useless-concat | |
| console.log(`%c${key}`, "color:red;", "changed", changesObj[key]); | |
| } | |
| console.groupEnd(); | |
| } | |
| } | |
| previousProps.current = props; | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment