Strange behaviour with dispatch function when using useReducer hook

reasonreact

#1

I am observing a rather strange behavior while using dispatch function of useReducer hook. I have created a small nit that reproduces this case. https://tinyurl.com/wnso6m7.

The problem seems to be that dispatch function doesn’t wait for the reducer to finish. So if I call another function after calling dispatch, that function seems to complete before the earlier called dispatch function, i.e. given below,

dispatch(EnableValidation);
validateInput();

validateInput() seems to complete before dispatch.

Is this an expected behaviour?

Here is the log trace of the behavior from the above mentioned nit.

reducer 
validateCounterName() 
ON BLUR 
reducer 
validateCounterName() 
ON CHANGE 
reducer 
validateCounterName() 
ON CHANGE 
reducer 
validateCounterName() 
ON CHANGE 
validateCounterName() 
reducer 
ON CHANGE 

As you can see the almost always the reducer is called after validateCounterName. However, in the code (line 46 - 56) it is the dispatch function that is called before the validateCounterName.

Any ideas what is happening?


#2

I believe this issue was resolved in the Discord chat. But for the benefit of anyone else browsing:

This isn’t a Reason issue specifically. In React, state updates are asynchronous. When you call dispatch, the next line of code will likely execute before the dispatch function has completed.

The solution is to put your validateInput function inside a useEffect hook:

React.useEffect1(
  () => {
    validateInput(state);
    None;
  },
  [|state|]
);

validateInput will only execute when React detects that state has updated.


#3

Thanks. :ok_hand: