By calling setB and someOtherOperation, one could potentially end up with unexpected results, errors or dealing with old state values.
To avoid this, want to update the dependency array in useEffect, and run a callback whenever a state has changed.
Side note:
I think many developers probably miss the ease of this with class based components. Which with the same component in class form would declare a callback with this.setState({ a: a + 1}, this.updateB)
Now one would think that just add b as another dependency. But we'd run into a problem.
Everything inside the useEffect method is going to get run, how do we determine which callback we mean to run?
This is sort of mimicking reducers. It might work for small apps. When dealing with larger apps, that's where reducers come in very handy. Read more here: https://react.dev/reference/react/useReducer
Disclaimer: I didn't run any of the above code for syntax errors.
Important: "Updating a React component’s state is asynchronous. It does not happen immediately."
Here you go @maxsibilla and @tjmadonna. Tuesday's assignment done. I was curious. :)
Say we have the following context and accompanying component (to save space didn't write any import or export statements):
By calling
setB
andsomeOtherOperation
, one could potentially end up with unexpected results, errors or dealing with old state values.To avoid this, want to update the dependency array in
useEffect
, and run a callback whenever a state has changed.Side note: I think many developers probably miss the ease of this with class based components. Which with the same component in class form would declare a callback with
this.setState({ a: a + 1}, this.updateB)
Now one would think that just add
b
as another dependency. But we'd run into a problem. Everything inside theuseEffect
method is going to get run, how do we determine which callback we mean to run?We could just add a new
useEffect
:I think it is obvious how this could potentially get very messy with a large app. So maybe want to group related values together.
This is sort of mimicking reducers. It might work for small apps. When dealing with larger apps, that's where reducers come in very handy. Read more here: https://react.dev/reference/react/useReducer
Disclaimer: I didn't run any of the above code for syntax errors.