useReducer hook in react

useReducer hook in react

useReducer hook in react

The useReducer hook allows you to manage complex state in a functional component. It’s similar to the useState hook, but instead of a simple value, it takes a reducer function and an initial state.


Here’s an example of how to use useReducer to manage a shopping cart:

import React, { useReducer } from 'react';

function cartReducer(state, action) {
  switch (action.type) {
    case 'add':
      return [...state, action.payload];
    case 'remove':
      return state.filter(item => item.id !== action.payload.id);
    default:
      return state;
  }
}

function ShoppingCart() {
  const [cart, dispatch] = useReducer(cartReducer, []);

  const addItem = (item) => {
    dispatch({ type: 'add', payload: item });
  }

  const removeItem = (item) => {
    dispatch({ type: 'remove', payload: item });
  }

  return (
    <div>
      <h2>Shopping Cart</h2>
      <ul>
        {cart.map(item => (
          <li key={item.id}>
            {item.name} - ${item.price}
            <button onClick={() => removeItem(item)}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick={() => addItem({ id: 1, name: 'Item 1', price: 9.99 })}>Add Item</button>
    </div>
  );
}

In this example, we define a cartReducer function that takes a state and an action and returns a new state based on the action type. We then use the useReducer hook to manage the cart state with the cartReducer function.

We also define two functions, addItem and removeItem, that dispatch actions to the cartReducer to add or remove items from the cart state.

Finally, we render the shopping cart with the cart items and buttons to add or remove items. When the buttons are clicked, the addItem or removeItem functions are called to update the cart state using the dispatch function returned by the useReducer hook.


Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts