Chris Jarling

Fullstack Engineer

Detect changes in useEffect dependencies

🚧 Work in ProgressThis page is still work in progress. Information might be incomplete, formatting and grammar might be off.

Taken from this StackOverflow answer

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, [effectHook, ...dependencies])
}

There also seems to be use-what-changed which probably is a lot more reliable, but have not used it yet.

Last update: 16th Oct, 2023
© 2024 Chris Jarling