Created
November 18, 2022 17:45
-
-
Save yulioaj290/ad42fb93f44e136fe9a856916cf3553b to your computer and use it in GitHub Desktop.
useEffectDebug is a custom hook for React that work silimar as useEffect. This hook give information about what dependency changes on each execution, and the old and new values for each changed dependency.
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
import React, { useEffect } from 'react' | |
import { isEqual } from 'lodash' | |
const usePrevious = (value, defaultValue) => { | |
const ref = React.useRef() | |
React.useEffect(() => { | |
ref.current = value | |
}) | |
return ref.current || defaultValue | |
} | |
const useEffectDebug = (effectHook, dependencies, dependencyNames = [], debug = false) => { | |
const previousDeps = usePrevious(dependencies, []) | |
const changedDeps = dependencies.reduce((result, dependency, index) => { | |
if (!isEqual(dependency, previousDeps[index])) { | |
const keyName = dependencyNames[index] || index | |
return { | |
...result, | |
[keyName]: { | |
before: previousDeps[index], | |
after: dependency, | |
}, | |
} | |
} | |
return result | |
}, {}) | |
if (debug && Object.keys(changedDeps).length) { | |
console.log('[use-effect-debugger] ', changedDeps) | |
} | |
useEffect(() => effectHook(changedDeps), dependencies) | |
} | |
export default useEffectDebug |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment