CodeBlanks Logo Icon CodeBlanks

Cart context

Write a provider that wraps the cart reducer with context.

Cart context

This lesson writes the CartProvider component. It takes state and dispatch from useReducer and wraps them in two separate contexts.

CartStateContext holds only state, CartDispatchContext only dispatch. This matters for performance: components using only dispatch don't react to state changes.

Components read state with useContext(CartStateContext) and dispatch with useContext(CartDispatchContext). Multiple components can share the same cart; managed from one place.

Nested Provider

Inside the CartProvider body, two Providers nest: outer CartStateContext.Provider, inner CartDispatchContext.Provider. Content comes from the children prop.

This pattern lets the cart be dispatched from anywhere in the app. A product card calls dispatch({ '{ type: "ADD", payload: product }' }); a summary component reads state.total. The flow is one-way and predictable.

Putting the Provider high in the tree is enough; all sub-components benefit. For multiple carts, use multiple Providers.

Practice Write CartProvider

Complete the skeleton. Write a CartProvider component. Take ({ '{ children }' }). Call useReducer(cartReducer, { '{ items: [], total: 0 }' }); destructure as [state, dispatch]. Return <CartStateContext.Provider value={ '{ state }' }> wrapping <CartDispatchContext.Provider value={ '{ dispatch }' }>{ '{ children }' }</CartDispatchContext.Provider></CartStateContext.Provider>. Export it.

Starter code

App.jsx
import { useReducer, createContext } from "react";

// Write the CartProvider component here

Sample solution

App.jsx
import { useReducer, createContext } from "react";

const CartStateContext = createContext(null);
const CartDispatchContext = createContext(null);

function CartProvider({ children }) {
  const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
  return (
    <CartStateContext.Provider value={state}>
      <CartDispatchContext.Provider value={dispatch}>
        {children}
      </CartDispatchContext.Provider>
    </CartStateContext.Provider>
  );
}

export default CartProvider;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does CartStateContext carry?

  • items
  • dispatch
  • actions
  • state Correct answer

Explanation: CartStateContext carries state.

2 Why two contexts

Question
Two contexts are used for ____.
Answer
Two contexts are used for performance.

Explanation: Two contexts for performance.

3 Match the CartProvider parts

Term Meaning
useReducer [state, dispatch]
CartStateContext state
CartDispatchContext dispatch
children content

All lessons in Intermediate