The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently.
counterReducer: A reducer function that handles two actions, INCREMENT and DECREMENT, updating the count value accordingly.
dispatch: This function triggers the reducer with the action type (INCREMENT or DECREMENT), which updates the state.
2. Managing Complex State with Multiple Actions
For more complex state management, you can use useReducer to handle actions that affect different parts of the state, such as managing a form or multiple values at once.
Output
In this example
formReducer: The reducer function handles three actions: SET_NAME, SET_AGE, and SUBMIT. Each action updates the corresponding part of the state.
dispatch: Dispatches actions to modify the state (e.g., setting the name or age, or marking the form as submitted).
When to Use useReducer
The state logic is complex and involves multiple sub-values or requires sophisticated updates.
You need to manage state transitions in a predictable manner (such as when working with forms or handling multiple actions).
You have multiple state variables that depend on each other and need to be updated together.
The logic for updating the state is not just a simple assignment but involves computations, conditions, or complex updates.