Last active
January 20, 2024 02:07
-
-
Save latobibor/8d347ae805b848b12a5d7280c3f8dd72 to your computer and use it in GitHub Desktop.
React dependency spy
This file contains 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
/** | |
* Ever wondered what triggered a rerendering in React? | |
* Who was the killer? Which dependency got updated? | |
* This is a very stupid little code that can help you debug the issue. | |
*/ | |
import { useRef } from 'react'; | |
type DependenciesObject = { | |
[dependencyName: string]: any; | |
}; | |
export function useDependencySpy(dependenciesObject: DependenciesObject) { | |
const listOfRefs = Object.entries(dependenciesObject).map(([key, value]) => ({ key, originalObject: useRef(value) })); | |
listOfRefs.forEach((ref) => { | |
if (!Object.is(ref.originalObject.current, dependenciesObject[ref.key])) { | |
console.info(`[${ref.key}] variable reference has changed!`); | |
ref.originalObject.current = dependenciesObject[ref.key]; | |
} | |
}); | |
} | |
// usage: | |
function MyComponent() { | |
const memoedThingThatShouldNotChange = useMemo(() => computeSomething(a, b), [a, b]); | |
useDependencySpy({ a, b }); | |
// just a random UI | |
return <div>JSON.stringify(memoedThingThatShouldNotChange)</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment