Skip to content

Instantly share code, notes, and snippets.

@indiejoseph
Created August 14, 2021 14:33
Show Gist options
  • Save indiejoseph/0281d3d0d9bc7ad8b184afba9b6445cf to your computer and use it in GitHub Desktop.
Save indiejoseph/0281d3d0d9bc7ad8b184afba9b6445cf to your computer and use it in GitHub Desktop.
const usePrevious = <T extends Record<string, any>>(value: T, initialValue: T) => {
const ref = useRef(initialValue);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const useEffectDebugger = (
effectHook: React.EffectCallback,
dependencies: any[],
dependencyNames: string[] = []
) => {
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