Skip to content

Instantly share code, notes, and snippets.

@andreloureiro
Created June 11, 2024 16:42
Show Gist options
  • Save andreloureiro/0a84ef8ef9d37b478c6b03b50c629757 to your computer and use it in GitHub Desktop.
Save andreloureiro/0a84ef8ef9d37b478c6b03b50c629757 to your computer and use it in GitHub Desktop.
useEffect debugger
/**
* From https://stackoverflow.com/a/59843241/24205983
*
* Example 1
*
* Before:
* ```
* useEffect(() => {
* // useEffect code here...
* }, [dep1, dep2])
* ```
*
* After:
* ```
* useEffectDebugger(() => {
* // useEffect code here...
* }, [dep1, dep2])
* ```
*
* Console output:
* ```
* {
* 1: {
* before: 'foo',
* after: 'bar'
* }
* }
* ```
*
* Example 2
*
* Before:
* ```
* useEffect(() => {
* // useEffect code here...
* }, [dep1, dep2])
* ```
*
* After:
* ```
* useEffectDebugger(() => {
* // useEffect code here...
* }, [dep1, dep2], ['dep1', 'dep2'])
* ```
*
* Console output:
* ```
* {
* dep2: {
* before: 'foo',
* after: 'bar'
* }
* }
* ```
*/
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