Last active
June 8, 2021 20:52
-
-
Save kddial/82a973cbb4b14d8cfa49b4e9b197e539 to your computer and use it in GitHub Desktop.
useEffectDebugger for comparing dependency list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source: https://stackoverflow.com/a/59843241 | |
const usePrevious = (value, initialValue) => { | |
const ref = React.useRef(initialValue); | |
React.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); | |
} | |
React.useEffect(effectHook, dependencies); | |
}; | |
/** | |
Example Usage | |
Before: | |
useEffect(() => { | |
// useEffect code here... | |
}, [dep1, dep2]) | |
After: | |
useEffectDebugger(() => { | |
// useEffect code here... | |
}, [dep1, dep2], ['dep1', 'dep2']) | |
Console output: | |
{ | |
dep2: { | |
before: 'foo', | |
after: 'bar' | |
} | |
} | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment