Skip to content

Instantly share code, notes, and snippets.

@markselby9
Last active July 8, 2024 16:04
Show Gist options
  • Save markselby9/59640ec27eba6c7a585c6aa71c6522ce to your computer and use it in GitHub Desktop.
Save markselby9/59640ec27eba6c7a585c6aa71c6522ce to your computer and use it in GitHub Desktop.
A `useEffectDebugger` hook to debug which dependency changed causing `useEffect` hook to fire
// a code snippet living in a component
// source: https://stackoverflow.com/a/59843241/3600510
const usePrevious = (value, initialValue) => {
const ref = useRef(initialValue);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const useEffectDebugger = (effectHook, dependencies, dependencyNames = []) => {
const previousDeps = usePrevious(dependencies, []);
const changedDeps = dependencies.reduce((accum, dependency, index) => {
if (dependency !== previousDeps[index]) {
const keyName = dependencyNames[index] || index;
return {
...accum,
[keyName]: {
before: previousDeps[index],
after: dependency,
},
};
}
return accum;
}, {});
if (Object.keys(changedDeps).length) {
console.log('[use-effect-debugger] ', changedDeps);
}
useEffect(effectHook, dependencies);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment