5

I am using useReducer, and want to dispatch 2 times. Is it guaranteed that the state fed to the reducer the second time is output of the first update?

If I do this

dispatch({ type:"RESET" }); // set state to default state
dispatch({ type:"LOAD", id: "abc" }); // set id

Can I be sure that state will be { ...defaultState, id: "abc" }?

swenedo
  • 3,074
  • 8
  • 30
  • 49
  • assuming your reducers function as expected, then yes. – Joseph D. Aug 29 '19 at 09:46
  • The way you show the code here then yes, if you have both dispatch in different `useEffect` then no. – HMR Aug 29 '19 at 09:49
  • @HMR They are in the same `useEffect`. My experience so far is that they behave like I expected, but want to be sure. Do you know if this is documented? I haven't found it... – swenedo Aug 29 '19 at 09:59
  • I thought dispatching twice could run the following way: `dispatch => reducer => render => useEffect => dispatch ...` and would be stuck in an infinite loop. But it doesn't seem to do so. The function in usEffect will finish before re rendering so you can dispatch multiple times in `useEffect`. The infinite loop does not occur [in this example](https://codesandbox.io/s/eager-cori-fsg3d) – HMR Aug 29 '19 at 12:04
  • 1
    Yep - no infinite loop. I wasn't worried about that because my effect doesn't depend on anything from the state. I would like to read a **guarantee** from React that dispatch always use state from previous reducer run. It seems like it works that way. – swenedo Aug 30 '19 at 08:54
  • +1, I also would like to know this. I have several reducers that operate more or less together, with one being called for a finalization and another immediately after to save that finalized object, and would like to have a guarantee that the object will be finalized before that save is ran – Werlious Aug 15 '20 at 04:09

0 Answers0