The shopping cart system uses React Context API to manage cart state globally across the application, allowing users to add, remove, and manage product quantities.
Cart Context Overview
The cart is implemented using React’s Context API with a reducer pattern for state management.
src/context/CartContext.js
import React , { createContext , useContext , useReducer } from 'react' ;
const CartContext = createContext ();
const initialState = {
items: []
};
The cart context is defined in src/context/CartContext.js and should wrap your entire application.
Cart Provider Setup
Wrap your application with the CartProvider to enable cart functionality:
import { CartProvider } from './context/CartContext' ;
function App () {
return (
< CartProvider >
{ /* Your app components */ }
</ CartProvider >
);
}
Cart State Management
Cart Reducer
The cart uses a reducer to handle state updates:
src/context/CartContext.js
const cartReducer = ( state , action ) => {
switch ( action . type ) {
case 'ADD_ITEM' :
const existingItem = state . items . find ( item => item . id === action . payload . id );
if ( existingItem ) {
return {
... state ,
items: state . items . map ( item =>
item . id === action . payload . id
? { ... item , quantity: item . quantity + 1 }
: item
)
};
} else {
return {
... state ,
items: [ ... state . items , { ... action . payload , quantity: 1 }]
};
}
case 'REMOVE_ITEM' :
const item = state . items . find ( item => item . id === action . payload . id );
if ( item && item . quantity > 1 ) {
return {
... state ,
items: state . items . map ( item =>
item . id === action . payload . id
? { ... item , quantity: item . quantity - 1 }
: item
)
};
} else {
return {
... state ,
items: state . items . filter ( item => item . id !== action . payload . id )
};
}
case 'CLEAR_CART' :
return {
... state ,
items: []
};
default :
return state ;
}
};
Action Description Behavior ADD_ITEMAdd product to cart Increments quantity if exists, otherwise adds new item with quantity 1 REMOVE_ITEMRemove product from cart Decrements quantity, removes completely if quantity reaches 0 CLEAR_CARTEmpty entire cart Resets items array to empty
Cart Operations
Adding Items
Add a product to the cart or increment its quantity:
src/context/CartContext.js
const addItem = ( item ) => {
dispatch ({ type: 'ADD_ITEM' , payload: item });
};
Usage Example:
import { useCart } from '../context/CartContext' ;
function ProductCard ({ product }) {
const { addItem } = useCart ();
return (
< button onClick = { () => addItem ( product ) } >
Add to Cart
</ button >
);
}
Removing Items
Decrement quantity or remove item entirely:
src/context/CartContext.js
const removeItem = ( item ) => {
dispatch ({ type: 'REMOVE_ITEM' , payload: item });
};
Usage Example:
const { removeItem } = useCart ();
< button onClick = { () => removeItem ( product ) } >
Remove
</ button >
Clearing Cart
Remove all items from the cart:
src/context/CartContext.js
const clearCart = () => {
dispatch ({ type: 'CLEAR_CART' });
};
clearCart() is automatically called after a successful WhatsApp order to reset the cart.
Cart Utilities
Get Item Quantity
Check the quantity of a specific item in the cart:
src/context/CartContext.js
const getItemQuantity = ( itemId ) => {
const item = state . items . find ( item => item . id === itemId );
return item ? item . quantity : 0 ;
};
Get Total Items
Calculate total number of items across all products:
src/context/CartContext.js
const getTotalItems = () => {
return state . items . reduce (( total , item ) => total + item . quantity , 0 );
};
Example Output:
2x Fuska Su 19Lt = 2 items
1x Pınar Su 24x0.5L = 1 item
Total: 3 items
Get Total Price
Calculate the total cart value:
src/context/CartContext.js
const getTotalPrice = () => {
return state . items . reduce (( total , item ) => {
// Extract number from price string (e.g., "25 TL" -> 25)
const price = parseFloat ( item . price . replace ( / [ ^ \d,.- ] / g , '' ). replace ( ',' , '.' )) || 0 ;
return total + ( price * item . quantity );
}, 0 );
};
The price parser handles various formats including “160 TL”, “160TL”, and “160,00 TL”.
Generate WhatsApp Message
Create a formatted message for WhatsApp orders:
src/context/CartContext.js
const getCartMessage = () => {
if ( state . items . length === 0 ) return '' ;
const itemMessages = state . items . map ( item =>
` ${ item . quantity } adet - ${ item . name } `
);
return ` ${ itemMessages . join ( ' \n ' ) } \n sipariş etmek istiyorum.` ;
};
Example Output:
2 adet - Fuska Su 19Lt Damacana
1 adet - Pınar Su 24x0.5L Şişe
sipariş etmek istiyorum.
useCart Hook
Access cart functionality in any component:
src/context/CartContext.js
export const useCart = () => {
const context = useContext ( CartContext );
if ( ! context ) {
throw new Error ( 'useCart must be used within a CartProvider' );
}
return context ;
};
Available Properties and Methods
const { items } = useCart ();
// Array of cart items with quantities
Complete Usage Example
Here’s a complete example of a cart summary component:
import { useCart } from '../context/CartContext' ;
function CartSummary () {
const {
items ,
getTotalItems ,
getTotalPrice ,
addItem ,
removeItem ,
clearCart
} = useCart ();
const totalItems = getTotalItems ();
const totalPrice = getTotalPrice ();
return (
< div className = "cart-summary" >
< h2 > Cart ( { totalItems } items) </ h2 >
{ items . map ( item => (
< div key = { item . id } className = "cart-item" >
< span > { item . name } </ span >
< div className = "quantity-controls" >
< button onClick = { () => removeItem ( item ) } > − </ button >
< span > { item . quantity } </ span >
< button onClick = { () => addItem ( item ) } > + </ button >
</ div >
< span > { item . price } </ span >
</ div >
)) }
< div className = "cart-total" >
< strong > Total: { totalPrice . toFixed ( 2 ) } TL </ strong >
</ div >
< button onClick = { clearCart } > Clear Cart </ button >
</ div >
);
}
Cart Item Structure
Each item in the cart has the following structure:
{
id : 11 ,
name : "Fuska Su 19Lt Damacana" ,
price : "160 TL" ,
image : "/images/f19.png" ,
imagePlaceholder : "🏺" ,
whatsappMessage : "Merhaba Sultan Su 19L damacana sipariş etmek istiyorum. Adresim: " ,
quantity : 2 // Added by cart context
}
The quantity field is added by the cart context and is not part of the original product data.
Best Practices
Single Source of Truth Always use the cart context for cart data. Never maintain separate cart state in individual components.
Error Boundaries Wrap cart-dependent components in error boundaries to handle potential context errors gracefully.
Memoization For performance, memoize cart calculations in components that don’t need real-time updates.
Persistence Consider adding localStorage persistence to maintain cart data across page refreshes.
Product Catalog Learn about the product data structure added to the cart
WhatsApp Ordering See how cart data is formatted for WhatsApp orders