Loading

Quipoin Menu

Learn • Practice • Grow

react / useReducer Hook
tutorial

useReducer Hook

When your component's state becomes complex with multiple sub-values or when the next state depends on the previous one in intricate ways `useState` might become messy. That's where `useReducer` comes in. It's like a mini Redux built into React.

What is useReducer?

`useReducer` is a React Hook that lets you manage state with a reducer function. A reducer is a pure function that takes the current state and an action, and returns the new state. It's perfect for complex state logic or when the next state depends on multiple conditions.

Think of `useReducer` as a more powerful version of `useState`. It's like having a mini state machine inside your component.

Syntax
const [state, dispatch] = useReducer(reducer, initialState);

Example: Shopping Cart
import React, { useReducer } from 'react';

<!-- Initial state -->
const initialState = { cart: [], total: 0 };

<!-- Reducer function -->
function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM':
      const newItem = action.payload;
      return {
        ...state,
        cart: [...state.cart, newItem],
        total: state.total + newItem.price
      };
    case 'REMOVE_ITEM':
      const itemId = action.payload.id;
      const itemToRemove = state.cart.find(item => item.id === itemId);
      return {
        ...state,
        cart: state.cart.filter(item => item.id !== itemId),
        total: state.total - (itemToRemove ? itemToRemove.price : 0)
      };
    case 'CLEAR_CART':
      return initialState;
    default:
      return state;
  }
}

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

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

  return (
    <div>
      <h2>Shopping Cart</h2>
      <button onClick={() => addItem({ id: 1, name: 'Laptop', price: 999 })}>
        Add Laptop
      </button>
      <ul>
        {state.cart.map(item => (
          <li key={item.id}>
            {item.name} - ${item.price}
            <button onClick={() => dispatch({ type: 'REMOVE_ITEM', payload: { id: item.id } })}>
              Remove
            </button>
          </li>
        ))}
      </ul>
      <p>Total: ${state.total}</p>
      <button onClick={() => dispatch({ type: 'CLEAR_CART' })}>Clear Cart</button>
    </div>
  );
}

When to Use useReducer vs useState

useStateuseReducer
Simple state (boolean, number, string)Complex state objects or arrays
State transitions are simpleState transitions involve multiple sub-values or logic
Fewer lines of codeMore predictable state updates

Two Minute Drill

  • `useReducer` manages complex state logic with a reducer function and actions.
  • The reducer takes the current state and an action, and returns the new state.
  • `dispatch` sends actions to the reducer to trigger state updates.
  • Use it when state transitions are complex or when the next state depends on multiple conditions.
  • It's especially useful for state that involves multiple sub-values (like a shopping cart, form state, or game state).

Need more clarification?

Drop us an email at career@quipoinfotech.com