The project uses React Context API for global state management. This provides a simple, effective way to manage application state without external libraries.
Why React Context?
Simple & Lightweight
No external dependencies, built into React
Perfect for E-commerce
Ideal for cart and wishlist state that needs to be shared across components
Server-Side Compatible
Works seamlessly with Next.js Server Components
Cart Context
File: src/contexts/CartContext.jsx
The Cart Context manages all shopping cart state and operations:
Using Cart Context
import { useCart } from "@/contexts/CartContext"; // Import Cart context
function MyComponent() { // My component to use cart context
const { addToCart, updateQuantity, removeItem, cartData } = useCart(); // Get add to cart, update quantity, remove item and cart data from cart context
await addToCart(productId, quantity); // Add product to cart with the given product id and quantity
await updateQuantity(itemKey, newQuantity); // Update quantity of the item with the given key to the new quantity
await removeItem(itemKey); // Remove item with the given key from the cart
}Cart Context Properties
| Property | Type | Description |
|---|---|---|
|
Object |
Complete cart data including items and totals |
|
Boolean |
True when cart is being fetched |
|
String |
Error message if cart operation fails |
|
Boolean |
True when cart is being updated |
|
Number |
ID of product currently being updated |
|
Number |
Number of unique items in cart |
|
Function |
Add product to cart |
|
Function |
Update item quantity |
|
Function |
Remove item from cart |
|
Function |
Clear entire cart |
|
Function |
Check if product is in cart |
|
Function |
Get cart item by product ID |
Add to Cart Example
"use client";
import { useCart } from "@/contexts/CartContext"; // Import Cart context
export default function AddToCartButton({ productId }) { // Client component to add to cart
const { addToCart, isUpdating } = useCart();
return (
addToCart(productId, 1)} disabled={isUpdating}>
Add to Cart
);
}Update Quantity Example
const { updateQuantity } = useCart(); // Get update quantity function from cart context
updateQuantity(itemKey, quantity + 1)}>+
updateQuantity(itemKey, quantity - 1)}>-Wishlist Context
File: src/contexts/WishlistContext.jsx
The Wishlist Context manages wishlist items stored in browser cookies:
Using Wishlist Context
import { useWishlist } from "@/contexts/WishlistContext";
const { toggle, isInWishlist } = useWishlist();
toggle(productId);
if (isInWishlist(productId)) { /* in wishlist */ }Wishlist Context Properties
| Property | Type | Description |
|---|---|---|
|
Array |
Array of product IDs in wishlist |
|
Function |
Add product ID to wishlist |
|
Function |
Remove product ID from wishlist |
|
Function |
Toggle product in/out of wishlist |
|
Function |
Check if product is in wishlist |
Wishlist Button Example
const { toggle, isInWishlist } = useWishlist(); // Get toggle and isInWishlist functions from wishlist context
toggle(productId)}> // Toggle product in/out of wishlist with the given product idProvider Setup
// app/layout.js
import { CartProvider } from "@/contexts/CartContext"; // Import Cart provider
import { WishlistProvider } from "@/contexts/WishlistContext"; // Import Wishlist provider
export default function RootLayout({ children }) { // Root layout to wrap pages and persist across navigation
return (
// Wrap pages with Cart provider
// Wrap pages with Wishlist provider
{children}
// Wrap pages with Wishlist provider
); // Return wrapped pages
}Optimistic Updates
The Cart Context uses optimistic updates for better UX:
- UI updates immediately when user interacts
- Request sent to server in background
- If request fails, UI reverts to previous state
- If request succeeds, UI reflects server state
Benefits: Optimistic updates make the app feel faster and more responsive, even with network latency.
State Persistence
Cart State
- Cart data is stored server-side in WooCommerce
- Cart token stored in httpOnly cookies
- Cart persists across page refreshes and browser sessions
- Cart expires after period of inactivity
Wishlist State
- Wishlist stored in browser cookies
- Persists across page refreshes
- Not synced with server (client-side only)
Best Practices
- Use Context Selectively: Only use Context for truly global state
- Handle Loading States: Always show loading indicators during async operations
- Handle Errors: Display user-friendly error messages
- Optimistic Updates: Update UI immediately, sync with server
- Debounce Requests: Avoid rapid-fire API calls
Next Steps: Learn about Cart Management and Authentication to use state management effectively.