Created
May 3, 2022 15:24
-
-
Save mrampazz/6830166a458b6d2fda107740ee775126 to your computer and use it in GitHub Desktop.
Hook to check which dep has changed on useEffect call
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
// usage: useEffectDebugger(callback, deps) | |
const usePrevious = (value: any, initialValue: any) => { | |
const ref = useRef(initialValue); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref.current; | |
}; | |
const useEffectDebugger = (effectHook: any, dependencies: any, dependencyNames = []) => { | |
const previousDeps = usePrevious(dependencies, []); | |
const changedDeps = dependencies.reduce((accum: any, dependency: any, index: any) => { | |
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