Reputation: 31
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} />
</>
)
}
Upvotes: 3
Views: 2107
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