search
HomeWeb Front-endJS TutorialState Management with useContext and useReducer in React: Building a Global Shopping Cart

State Management with useContext and useReducer in React: Building a Global Shopping Cart

Advanced State Management with useContext and useReducer in React: Building a Global Shopping Cart

In the previous article, we introduced the concept of combining useContext and useReducer to manage global state effectively in a React application. We demonstrated this by building a simple to-do list. Now, we’re going to take things up a notch and apply these concepts to a more complex, real-world example—a global shopping cart.

This guide will cover how to manage multiple states and actions, such as adding, updating, and removing items, and calculating totals—all while keeping the application scalable and performant.

In this second part, you’ll learn to:

  1. Handle more complex states using useReducer.
  2. Create a flexible context provider to manage state and actions globally.
  3. Implement advanced reducer functions to perform calculations and handle various types of actions.
  4. Optimize component performance with memoization for better performance.

Let's dive in!


Project Overview: A Global Shopping Cart

Our shopping cart application will have:

  • Product List: A set of items available to add to the cart.
  • Cart Functionality: Users can add, update, and remove items in the cart.
  • Cart Totals: Calculate and display the total items and the total price.

We’ll start by setting up the context and reducer, then build components to showcase the features.

Setup and Initial Files

To get started, initialize your React project and set up a basic folder structure:

src/
├── CartContext.js
├── CartProvider.js
├── ProductList.js
├── Cart.js
└── App.js

Step 1: Create the Initial State and Reducer

We’ll start with an initial state that represents an empty cart and a set of sample products.

Initial State:

// Initial state structure
const initialState = {
  products: [
    { id: 1, name: "Product A", price: 30 },
    { id: 2, name: "Product B", price: 20 },
    { id: 3, name: "Product C", price: 50 }
  ],
  cart: [],
  totalItems: 0,
  totalPrice: 0
};

Reducer Function:

We’ll set up a cartReducer function to handle various actions such as adding items, updating item quantities, removing items, and calculating totals.

src/
├── CartContext.js
├── CartProvider.js
├── ProductList.js
├── Cart.js
└── App.js

Explanation

  • ADD_TO_CART: Adds an item to the cart, increasing the quantity if it already exists.
  • REMOVE_FROM_CART: Removes an item based on its ID.
  • UPDATE_QUANTITY: Updates the quantity of an item in the cart.
  • CALCULATE_TOTALS: Calculates the total number of items and the total price of the cart.

Step 2: Create Context and Provider

Now, we’ll create a context and provider to pass our state and dispatch function globally. This will allow all components to access the cart state and actions.

CartContext.js

// Initial state structure
const initialState = {
  products: [
    { id: 1, name: "Product A", price: 30 },
    { id: 2, name: "Product B", price: 20 },
    { id: 3, name: "Product C", price: 50 }
  ],
  cart: [],
  totalItems: 0,
  totalPrice: 0
};

Step 3: Building the Components

With the provider and context set up, we can now create components for the Product List and the Cart.


ProductList Component

The ProductList component will display a list of available products and allow users to add products to the cart.

ProductList.js

function cartReducer(state, action) {
  switch (action.type) {
    case "ADD_TO_CART": {
      const item = state.cart.find(item => item.id === action.payload.id);
      const updatedCart = item
        ? state.cart.map(cartItem =>
            cartItem.id === item.id
              ? { ...cartItem, quantity: cartItem.quantity + 1 }
              : cartItem
          )
        : [...state.cart, { ...action.payload, quantity: 1 }];

      return { ...state, cart: updatedCart };
    }

    case "REMOVE_FROM_CART": {
      const updatedCart = state.cart.filter(item => item.id !== action.payload);
      return { ...state, cart: updatedCart };
    }

    case "UPDATE_QUANTITY": {
      const updatedCart = state.cart.map(item =>
        item.id === action.payload.id
          ? { ...item, quantity: action.payload.quantity }
          : item
      );
      return { ...state, cart: updatedCart };
    }

    case "CALCULATE_TOTALS": {
      const { totalItems, totalPrice } = state.cart.reduce(
        (totals, item) => {
          totals.totalItems += item.quantity;
          totals.totalPrice += item.price * item.quantity;
          return totals;
        },
        { totalItems: 0, totalPrice: 0 }
      );
      return { ...state, totalItems, totalPrice };
    }

    default:
      return state;
  }
}

Cart Component

The Cart component displays items in the cart, allows updating quantities, removing items, and shows the total items and price.

Cart.js

import React, { createContext, useReducer } from 'react';

export const CartContext = createContext();

export function CartProvider({ children }) {
  const [state, dispatch] = useReducer(cartReducer, initialState);

  return (
    <cartcontext.provider value="{{" state dispatch>
      {children}
    </cartcontext.provider>
  );
}

Explanation

  • handleRemove: Removes an item from the cart.
  • handleUpdateQuantity: Updates the quantity of a selected item.
  • Total Items and Price: The cart component displays the total items and price based on the calculated values in the state.

Step 4: Wrap the App with the Provider

To ensure all components can access the cart state, wrap the entire app in CartProvider.

App.js

import React, { useContext } from 'react';
import { CartContext } from './CartContext';

function ProductList() {
  const { state, dispatch } = useContext(CartContext);

  const handleAddToCart = (product) => {
    dispatch({ type: "ADD_TO_CART", payload: product });
    dispatch({ type: "CALCULATE_TOTALS" });
  };

  return (
    <div>
      <h2 id="Products">Products</h2>
      <ul>
        {state.products.map(product => (
          <li key="{product.id}">
            {product.name} - ${product.price}
            <button onclick="{()"> handleAddToCart(product)}>Add to Cart</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ProductList;

Final Touches: Memoization and Optimization

As your application grows, optimizing performance is essential. Here are a few tips:

  1. Memoize Components: Use React.memo to prevent unnecessary re-renders of components that depend on state.
  2. Separate Contexts: Consider separating product and cart contexts if they become too large, allowing more targeted state updates.

Recap and Conclusion

In this advanced guide, we used useContext and useReducer to manage a global shopping cart. Key takeaways include:

  1. Complex State Management: useReducer simplifies managing complex actions and calculations.
  2. Global State with useContext: Makes state accessible across the component tree.
  3. Scalable Patterns: Separating state and actions in contexts allows for cleaner, more modular code.

Try applying this approach to your projects, and see how it improves the scalability and performance of your applications. Happy coding! ?

The above is the detailed content of State Management with useContext and useReducer in React: Building a Global Shopping Cart. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.