Dispatching states
In this chapter, we have learned that the dispatch
function, provided by the useState
hook, allows us to request a change of state any time we want to. The input argument that represents an action can be a string, a number, an object, an array, or any JavaScript expression:
dispatch(state) dispatch({ state }) dispatch([ state ]) dispatch(null)
We know that, internally, the input argument supports a functional update format as well:
dispatch(state => state + 1)
The benefit of using a functional update format here is that it has an opportunity to read the previous state before making a move toward the next state. This sometimes becomes useful if you build a new state that requires an old state.
A dispatched state is compared with the current state before making a final call if it changes. This means that not all dispatches end up with a state change. Take the following code as an example...