Skip to content

Instantly share code, notes, and snippets.

@litera
Created November 25, 2022 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save litera/b25f0b9808170f6414e5740faa6757e2 to your computer and use it in GitHub Desktop.
Save litera/b25f0b9808170f6414e5740faa6757e2 to your computer and use it in GitHub Desktop.
`useEffect` that also logs which dependency change triggered it
const usePrevious = (value, initialValue) => {
const ref = useRef(initialValue);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export 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