React State Tools for a Cart: Which Fits?
In this article
The best React state tool for a shopping cart is a combination of local state with a reducer for the cart itself and server state management (like React Query or SWR) for fetching product data. For most applications, a simple useReducer hook is sufficient; you only need a dedicated state management library like Zustand or Redux when the cart must be shared across many components or persisted with complex logic.
Understanding the Cart's State Needs
A shopping cart is a classic example of client-side state that changes frequently. It needs to track items, quantities, prices, and totals. The core operations are adding, removing, updating quantities, and clearing the cart. These operations are deterministic and can be expressed as pure functions that take the current state and an action, returning a new state. This is exactly what a reducer does.
The cart state is also transient—it usually exists only for the duration of the user's session. While you might persist it to localStorage or a backend, the live, in-memory state is what the UI reads. This distinguishes it from server state (like product listings, user profiles, or inventory levels) which is fetched from an API and may be stale or shared across users.
Why useReducer Is Often the Best Fit
React's built-in useReducer hook is designed for exactly this kind of state: complex, with multiple sub-values and transitions. Unlike useState, which can become unwieldy when you have many related pieces of state (like items, quantities, and a promo code), a reducer centralizes all update logic in one function. This makes it easier to test and debug.
For example, a typical cart reducer might look like this:
function cartReducer(state, action) {
switch (action.type) {
case 'ADD_ITEM':
return { ...state, items: [...state.items, action.item] };
case 'REMOVE_ITEM':
return { ...state, items: state.items.filter(i => i.id !== action.id) };
case 'UPDATE_QTY':
return { ...state, items: state.items.map(i => i.id === action.id ? { ...i, qty: action.qty } : i) };
default:
return state;
}
}This pattern is predictable and works well for a cart that lives in a single component (like a checkout page) or is passed down via context. It avoids adding an external dependency for something React already handles well.
When to Consider Zustand or Redux
As your app grows, you might find that many components need access to the cart—a header with a badge, a product page with an "Add to Cart" button, and a cart drawer. If you're already using Context API, you can pass the reducer down, but Context has a performance pitfall: every consumer re-renders when the context value changes, even if they only need a slice of it.
Libraries like Zustand or Redux solve this by allowing components to subscribe to specific parts of the state. Zustand is particularly lightweight and requires minimal boilerplate. Redux is more heavyweight but offers devtools and middleware out of the box. If your cart has complex logic like syncing with a backend, handling optimistic updates, or supporting multi-vendor carts, a dedicated store might be worth the extra dependency.
However, for a typical e-commerce site, the added complexity of Redux is rarely justified. Zustand is a good middle ground if you need global access without the boilerplate.
Server State: Don't Mix It with Cart State
A common mistake is to put product data (like prices and descriptions) into the same state container as the cart. Product data is server state—it comes from an API and can change. Mixing it with client-side cart state leads to duplication and staleness issues.
Instead, use a dedicated server-state library like React Query or SWR. These tools handle caching, background refetching, and request deduplication. For example, when a user adds an item to the cart, you only need to store the product ID and quantity in the cart state. The product details can be fetched from the server using React Query, which will cache them and update them when needed.
This separation keeps your cart reducer simple and your product data fresh. It also makes it easier to invalidate cache when inventory changes.
Common Pitfalls and How to Avoid Them
- Stale closures: When using
useReducerinside a component, ensure you're not capturing old state in event handlers. Use the functional update form or dispatch actions that carry all needed data. - Mutating state directly: Always return a new object/array from the reducer. Mutating the existing state can cause bugs that are hard to trace.
- Not persisting the cart: If you want the cart to survive a page refresh, you need to sync it with
localStorageor a backend. This is often done in auseEffectthat saves the state on change. - Over-engineering: Adding Redux just for a cart is overkill. Start with
useReducerand only introduce a global store when you actually need cross-component updates without prop drilling.
How to Choose the Right Tool
Here's a decision guide:
- Cart is local to one page (e.g., checkout): Use
useReducer. - Cart is needed in many components (header, product page, cart page): Use
useReducer+ Context, or Zustand if you have many consumers. - Cart has complex async logic (e.g., syncing with a backend, applying promo codes from a server): Consider Zustand with middleware, or Redux Toolkit.
- You already use Redux for other global state: Keep the cart in Redux for consistency.
- You need to fetch product data: Use React Query or SWR for that, not your cart state.
Frequently Asked Questions
Is useState enough for a cart?
For a very simple cart with only one or two items, useState might work, but as soon as you have multiple items and operations, you'll find yourself writing multiple state variables and update functions. A reducer consolidates that logic and is easier to maintain.
Should I use Redux Toolkit or plain Redux?
If you choose Redux, use Redux Toolkit. It reduces boilerplate significantly and includes best practices like Immer for immutable updates. Plain Redux requires a lot of manual setup that is unnecessary for most projects.
How do I persist the cart to localStorage?
You can use a useEffect that runs whenever the cart state changes, serializing it to localStorage. On initial load, read from localStorage and use that as the initial state. Be careful to handle JSON parsing errors and versioning if your cart shape changes.
Can I use React Query for the cart itself?
React Query is for server state, not client state. While you could technically use it to cache cart mutations, it's not designed for that. It's better to keep the cart in local state and use React Query for product data and other API calls.
What about using a state machine like XState?
XState is powerful for complex state logic, but for a cart, it's usually overkill. A cart is a simple data structure with a few actions, not a complex state machine. You'd be adding a lot of complexity for little benefit.
Does the choice of state tool affect performance?
Yes, but usually not significantly. Context can cause unnecessary re-renders if not used carefully. Zustand and Redux with selectors can prevent that. However, for a typical cart, the performance difference is negligible. Focus on correctness first.