Created
May 23, 2025 20:54
-
-
Save nikolaskhodov/3cf2616f02c3c083892109b76cb415ac to your computer and use it in GitHub Desktop.
Track changed hook dependencies in React
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 { DependencyList, useRef } from 'react'; | |
| export function useTrackChangedDependencies( | |
| dependencies: Record<string, any>, | |
| location = 'unknown location' | |
| ): DependencyList { | |
| const prevDependencies = useRef<Record<string, any> | undefined>(); | |
| if (prevDependencies.current !== undefined) { | |
| const changedDependencies = Array.from(Object.entries(dependencies)) | |
| .map<[string, any, any] | undefined>(([key, dependency]) => | |
| prevDependencies!.current[key] !== dependency | |
| ? [key, prevDependencies!.current[key], dependency] | |
| : undefined | |
| ) | |
| .filter(Boolean); | |
| if (changedDependencies.length > 0) { | |
| console.log(`Changed dependencies in ${location}`); | |
| console.table(changedDependencies); | |
| } | |
| } | |
| prevDependencies.current = dependencies; | |
| return Object.entries(dependencies).reduce<any[]>((list, entry) => { | |
| list.push(entry[1]); | |
| return list; | |
| }, []); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment