useReducer
An alternative to useState.
Returns the current state paired with a dispatch method (similar to Redux).
useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
useReducer also lets you optimize performance for components that trigger deep updates.
There are two different ways to initialize useReducer state.
The simplest way is to pass the initial state as a second argument:
const [state, dispatch] = useReducer(reducer, {count: initialCount});
If you return the same value from a Reducer Hook as the current state, React will bail out without rendering the children or firing effects.
Here's an example of this code:
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
Example
Count: 0