Ivan
Ivan

Reputation: 31

In useEffect hook, how to find out what event triggered state change?

I'm using useEffect hook to perform some sides effects after updating state. And that works perfectly fine, whenever child component invokes setOptions, useEffect fires as well.
I'm trying to figure out if there is a way to differentiate who updated options and based on that perform additonal work? More precisely, I would like to call another function in useEffect only if dependency was updated by specific component. Here's a dumbed down example of what I'm trying to do:

function App() {
  const [value, setValue] = useState({});
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const newValues = await getNewValues();

    setValue(newValues);

    // If options have been changed from ChildComponentA
    // Then doSomething() else nothing
  }, [options]); 

  function doSomething() {}

  return(
      <>
        <ChildComponentA handleChange={setOptions} />
        <ChildComponentB handleChange={setOptions} />
      </>
  )
}

The example may be weird, it's just an example of the problem I'm having. The main problem is that state can be changed by multiple events, and I can't tell which event triggered the state change.

Upvotes: 3

Views: 2107

Answers (1)

saarboledaz
saarboledaz

Reputation: 47

Maybe you could try adding an additional parameter to your options variable which would tell you from where the change was triggered, i.e options.child = 'A', would tell you it came from A and you could check that within the useEffect with a condition as if (options.child == 'A'), this of course would require options to be an object and not an array and that within the handleChange callback you do something like.

<ChildComponentA handleChange={(value) => {value.child ='A'; setOptions(value);}} />

Going deeper and as a personal recommendation, your app shouldn't aim to work different with the same state if it gets changed by one place or another since one of the main purposes of the state is to be a universal source of truth within your component and that each sub component that uses it treats it as such.

Upvotes: 1

Related Questions