Determine which dependency array variable caused useEffect hook to fire

JavascriptReactjsReact Hooks

Javascript Problem Overview


Is there an easy way to determine which variable in a useEffect's dependency array triggers a function re-fire?

Simply logging out each variable can be misleading, if a is a function and b is an object they may appear the same when logged but actually be different and causing useEffect fires.

For example:

React.useEffect(() => {
  // which variable triggered this re-fire?
  console.log('---useEffect---')
}, [a, b, c, d])

My current method has been removing dependency variables one by one until I notice the behavior that causes excessive useEffect calls, but there must be a better way to narrow this down.

Javascript Solutions


Solution 1 - Javascript

I ended up taking a little bit from various answers to make my own hook for this. I wanted the ability to just drop something in place of useEffect for quickly debugging what dependency was triggering useEffect.

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, dependencies);
};

Below are two examples. For each example, I assume that dep2 changes from 'foo' to 'bar'. Example 1 shows the output without passing dependencyNames and Example 2 shows an example with dependencyNames.

Example 1

Before:

useEffect(() => {
  // useEffect code here... 
}, [dep1, dep2])

After:

useEffectDebugger(() => {
  // useEffect code here... 
}, [dep1, dep2])

Console output:

{
  1: {
    before: 'foo',
    after: 'bar'
  }
}

The object key '1' represents the index of the dependency that changed. Here, dep2 changed as it is the 2nd item in the dependency, or index 1.

Example 2

Before:

useEffect(() => {
  // useEffect code here... 
}, [dep1, dep2])

After:

useEffectDebugger(() => {
  // useEffect code here... 
}, [dep1, dep2], ['dep1', 'dep2'])

Console output:

{
  dep2: {
    before: 'foo',
    after: 'bar'
  }
}

Solution 2 - Javascript

This library... @simbathesailor/use-what-changed , works like a charm!

  1. Install with npm/yarn and --dev or --no-save
  2. Add import:
import { useWhatChanged } from '@simbathesailor/use-what-changed';
  1. Call it:
// (guarantee useEffect deps are in sync with useWhatChanged)
let deps = [a, b, c, d]

useWhatChanged(deps, 'a, b, c, d');
useEffect(() => {
  // your effect
}, deps);

Creates this nice chart in the console:

https://github.com/simbathesailor/use-what-changed/raw/master/demoimages/indexandname.png" alt="image loaded from github" title="image loaded from github" />

There are two common culprits:

  1. Some Object being pass in like this:
// Being used like:
export function App() {
  return <MyComponent fetchOptions={{
    urlThing: '/foo',
    headerThing: 'FOO-BAR'
  })
}
export const MyComponent = ({fetchOptions}) => {
  const [someData, setSomeData] = useState()
  useEffect(() => {
    window.fetch(fetchOptions).then((data) => {
      setSomeData(data)
    })

  }, [fetchOptions])

  return <div>hello {someData.firstName}</div>
}

The fix in the object case, if you can, break-out a static object outside the component render:

const fetchSomeDataOptions = {
  urlThing: '/foo',
  headerThing: 'FOO-BAR'
}
export function App() {
  return <MyComponent fetchOptions={fetchSomeDataOptions} />
}

You can also wrap in useMemo:

export function App() {
  return <MyComponent fetchOptions={
    useMemo(
      () => {
        return {
          urlThing: '/foo',
          headerThing: 'FOO-BAR',
          variableThing: hash(someTimestamp)
        }
      },
      [hash, someTimestamp]
    )
  } />
}

The same concept applies to functions to an extent, except you can end up with stale closures.

Solution 3 - Javascript

UPDATE

After a little real-world use, I so far like the following solution which borrows some aspects of Retsam's solution:

const compareInputs = (inputKeys, oldInputs, newInputs) => {
  inputKeys.forEach(key => {
    const oldInput = oldInputs[key];
    const newInput = newInputs[key];
    if (oldInput !== newInput) {
      console.log("change detected", key, "old:", oldInput, "new:", newInput);
    }
  });
};
const useDependenciesDebugger = inputs => {
  const oldInputsRef = useRef(inputs);
  const inputValuesArray = Object.values(inputs);
  const inputKeysArray = Object.keys(inputs);
  useMemo(() => {
    const oldInputs = oldInputsRef.current;

    compareInputs(inputKeysArray, oldInputs, inputs);

    oldInputsRef.current = inputs;
  }, inputValuesArray); // eslint-disable-line react-hooks/exhaustive-deps
};

This can then be used by copying a dependency array literal and just changing it to be an object literal:

useDependenciesDebugger({ state1, state2 });

This allows the logging to know the names of the variables without any separate parameter for that purpose.

Edit useDependenciesDebugger

Solution 4 - Javascript

As far as I know, there's no really easy way to do this out of the box, but you could drop in a custom hook that keeps track of its dependencies and logs which one changed:

// Same arguments as useEffect, but with an optional string for logging purposes
const useEffectDebugger = (func, inputs, prefix = "useEffect") => {
  // Using a ref to hold the inputs from the previous run (or same run for initial run
  const oldInputsRef = useRef(inputs);
  useEffect(() => {
    // Get the old inputs
    const oldInputs = oldInputsRef.current;

    // Compare the old inputs to the current inputs
    compareInputs(oldInputs, inputs, prefix)

    // Save the current inputs
    oldInputsRef.current = inputs;

    // Execute wrapped effect
    func()
  }, inputs);
};

The compareInputs bit could look something like this:

const compareInputs = (oldInputs, newInputs, prefix) => {
  // Edge-case: different array lengths
  if(oldInputs.length !== newInputs.length) {
    // Not helpful to compare item by item, so just output the whole array
    console.log(`${prefix} - Inputs have a different length`, oldInputs, newInputs)
    console.log("Old inputs:", oldInputs)
    console.log("New inputs:", newInputs)
    return;
  }
  
  // Compare individual items
  oldInputs.forEach((oldInput, index) => {
    const newInput = newInputs[index];
    if(oldInput !== newInput) {
      console.log(`${prefix} - The input changed in position ${index}`);
      console.log("Old value:", oldInput)
      console.log("New value:", newInput)
    }
  })
}

You could use this like this:

useEffectDebugger(() => {
  // which variable triggered this re-fire?
  console.log('---useEffect---')
}, [a, b, c, d], 'Effect Name')

And you would get output like:

Effect Name - The input changed in position 2
Old value: "Previous value"
New value: "New value"

Solution 5 - Javascript

There’s another stack overflow thread stating you can use useRef to see a previous value.

https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state

Solution 6 - Javascript

Another Variant is that you can use multiple . this is an answer for people who didn't know that you can use multiple useEffect in single function

> useEffect

Like

React.useEffect(()=>{},[a])
React.useEffect(()=>{},[b])
React.useEffect(()=>{},[d])

you can have as much as you want from useEffect hook in one function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCumulo NimbusView Question on Stackoverflow
Solution 1 - JavascriptBradleyView Answer on Stackoverflow
Solution 2 - JavascriptDevin RhodeView Answer on Stackoverflow
Solution 3 - JavascriptRyan CogswellView Answer on Stackoverflow
Solution 4 - JavascriptRetsamView Answer on Stackoverflow
Solution 5 - JavascriptarcanereinzView Answer on Stackoverflow
Solution 6 - JavascriptAbdView Answer on Stackoverflow