Dispatching States

Learn how to implement dispatch function and handle state comparison in React for efficient state management.

Dispatch function in the useState hook

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:

// Dispatching a state value
dispatch(state);
// Dispatching an object with a state property
dispatch({ state });
// Dispatching an array with a state element
dispatch([state]);
// Dispatching null
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 moving toward the next state. This can sometimes become useful if we build a new state that requires an old state.

State comparison mechanism

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: ...