Skip to content

Instantly share code, notes, and snippets.

@yulioaj290
Created November 18, 2022 17:45
Show Gist options
  • Save yulioaj290/ad42fb93f44e136fe9a856916cf3553b to your computer and use it in GitHub Desktop.
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.
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