Skip to content

Instantly share code, notes, and snippets.

@crevulus
Last active September 13, 2022 11:05
Show Gist options
  • Save crevulus/9d1a8ae6202ed8c64feb18040eb34c08 to your computer and use it in GitHub Desktop.
Save crevulus/9d1a8ae6202ed8c64feb18040eb34c08 to your computer and use it in GitHub Desktop.
useEffect debugger to see which array deps changed.
const usePrevious = (value: any, initialValue: any) => {
const ref = useRef(initialValue);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export const useEffectDebugger = (effectHook: any, dependencies: any, dependencyNames = []) => {
const previousDeps = usePrevious(dependencies, []);
const changedDeps = dependencies.reduce((accum: any, dependency: any, index: number) => {
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