React useReducer Hook

React‘s useReducer Hook it is a built-in function that allows you to manage state in functional components using a reducer function. A reducer is a pure function that takes the previous state and an action, and returns the new state.

To use useReducer, you first need to create a reducer function that takes the previous state and an action, and returns the new state. The reducer function should be a pure function, meaning it should not mutate the previous state. Instead, it should return a new state object.

Here’s an example of how you might use useReducer to manage state in a counter component:

				
					import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

				
			

In this example, we first declare a reducer function that takes the previous state and an action, and returns the new state. The React’s useReducer hook function uses a switch statement to handle different action types. In this case, we have two action types: increment and decrement. When the increment action is dispatched, the reducer function returns a new state object with the count increased by 1. When the decrement action is dispatched, the reducer function returns a new state object with the count decreased by 1.

We then declare a Counter component that uses the useReducer hook to manage state. The useReducer hook takes the reducer function and an initial state object as arguments, and returns a state object and a dispatch function. The dispatch function is used to dispatch actions to the reducer function.

We then render the current count and two buttons that dispatch the increment and decrement actions when clicked. When an action is dispatched, the reducer function is called with the current state and the action, and returns the new state. The useReducer hook then updates the component with the new state, triggering a re-render.

useReducer is a powerful hook that allows you to manage state in functional components using a reducer function. By using it, you can write more declarative and predictable code that is easier to understand and maintain.

Join To Get Our Newsletter
Spread the love