How to use the useReducer hook for state management



Image not found!!

The useReducer hook in React is a powerful alternative to the useState hook when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. It is typically used to manage more complex state logic in a more centralized and predictable way.

Here's a basic example of how to use the useReducer hook:

jsx
import React, { useReducer } from 'react'; // Reducer function const reducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { // useReducer returns the current state and a dispatch function const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button> </div> ); }; export default Counter;

In this example:

  1. reducer: It's a function that takes the current state and an action as arguments and returns the new state. The action is an object with a type property indicating the type of operation to perform.

  2. useReducer(reducer, initialState): It returns an array with the current state and a dispatch function. The reducer is the function that calculates the next state based on the current state and the action, and initialState is the initial state of the component.

  3. dispatch: It's a function that you can call to dispatch an action, which triggers the state update.

  4. The component uses the state and dispatch function returned by useReducer to manage and update the state.

When the "Increment" or "Decrement" buttons are clicked, the dispatch function is called with the corresponding action, and the reducer function updates the state accordingly.

This example is quite simple, but you can use useReducer for more complex state logic by handling different action types in the reducer and updating the state accordingly.