Skip to content

Instantly share code, notes, and snippets.

@namtx
Forked from nvh95/useEffectDebugger.js
Created April 15, 2022 03:54
Show Gist options
  • Save namtx/314bce78d9603eddacc94a4aea6aed5c to your computer and use it in GitHub Desktop.
Save namtx/314bce78d9603eddacc94a4aea6aed5c to your computer and use it in GitHub Desktop.
Find which dependency cause useEffect to fire
// Credit to https://stackoverflow.com/a/59843241/3422559
import { useEffect, useRef } from "react";
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