Skip to content

Instantly share code, notes, and snippets.

@latobibor
Last active January 20, 2024 02:07
Show Gist options
  • Save latobibor/8d347ae805b848b12a5d7280c3f8dd72 to your computer and use it in GitHub Desktop.
Save latobibor/8d347ae805b848b12a5d7280c3f8dd72 to your computer and use it in GitHub Desktop.
React dependency spy
/**
* 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