Separating useEffect(s)
posted 2022.01.25 by Clark Wilkins, Simplexable

I had quite a bit of difficulty understanding how React triggers useEffect() to update the page, until I went back to the docs and read it again carefully.

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

This was my problem. For reference here (and for readers who are just getting started with Hooks like me, what you need to do is tie separate useEffect hooks to specific state changes like this:

const [monitoredValue1, setMonitoredValue1] = useState( desiredInitialValue );
const [monitoredValue2, setMonitoredValue2] = useState( desiredInitialValue );
  .
  .
  .
useEffect( () => { function1(); }, [monitoredValue1] );
useEffect( () => { function2(); }, [monitoredValue2] );

Now, when you setMonitoredValue1( someNewValue ). the first useEffect will run function1 again due to the state change. Similarly, setMonitoredValue2( someNewValue ) will trigger the second useEffect and run function2.

ADDENDUM 2022.02.11

This triggering cannot be based on an object as discussed here.