All My Faves
HomeBlogReactJs Add to Cart with Context and Reducer Hooks

ReactJs Add to Cart with Context and Reducer Hooks

22 28-01-2024
Muhammad Asad Ibrahim 742
ReactJs Add To Cart with Context and Reducer Hooks

ReactJs Add to Cart with Context and Reducer

ReactJs, a popular front-end development library introduced by Meta and the community (Facebook) in 2013, continues to be a robust choice for building dynamic user interfaces. In this blog, we’ll explore the implementation of context and reducer hooks with a real-time example showcasing an Add to Cart functionality.

Overview Of Context and Reducer Hooks:

What are Context Hooks?

Context hooks provide a solution to prop drilling, allowing you to pass information from a parent element to all child elements without the need for extensive prop passing. If you find yourself in a scenario where you need to send information to all child components within a parent component, context hooks can efficiently handle this through context providers.

What are reducer hooks?

Reducer hooks assist in managing state outside the component, offering a structured way to handle state logic. As your components grow, managing states within a single component can become overwhelming. For instance, in the context of an Add to Cart feature, handling product additions, quantity changes, removals, and price updates can be efficiently organized using a reducer hook. 

Example: Add to Cart Functionality

Let's dive into an example showcasing the implementation of an Add to Cart functionality using ReactJS.

Step 1: Create a React Project

         npx create-react-app add-to-cart               

Step 2: Folder Structure

Create the following folders within the ‘src’ directory

  • Components
  • Contexts
  • Layouts
  • Pages
  • Reducers

    Folder Structure

Step 3:Cart Context

In the cart context first import createContext,useContext,useReducer and useEffect from react.

import { createContextuseContextuseReduceruseEffect } from "react";

Create ‘CartContext’ constant using ‘createcontext’ 

const CartContext = createContext();

Define cart provider to pass values to components:

  const CartProvider = ({ children }) => {
    return ( <CartContext.Provider 
     value={{}}>
         {children}
  CartContext.Provider>     
  )}

Within ‘CartProvider’ define ‘AddToCart’ function:

 
 const initialstate = {   
 cart: getLocalCartData(), 
   totalItems: 0
};
 const CartProvider = ({ children }) => {
    const [statedispatch= useReducer(AddToCartReducerinitialstate); 
    const AddToCart = (idimagetitledescriptionpriceItemQuantity=> { 
       dispatch({
          type: 'addedtoCart',
          payload: {
          id: uuid(),
          image,
          title,
          description,
          price,
          quantity: ItemQuantity
          }
        });    
      }    
    return (
       <CartContext.Provider
    value={{ ...stateAddToCartDeleteItem }}>
           {children}
    CartContext.Provider>    
     ) 
 } 
  const useCartContext = () => { 
   return useContext(CartContext);
  } 
export { CartProvideruseCartContext }

In the above code reducer is used in AddToCart function body by dispatching the type and payload.  Here type can be anything you want to specify. It can be either AddItem, AddToCart etc and payload is the data we need to pass to reducer to update the state. State hold the information which is being stored. While initialstate holds the initial values within the state.

Step 4: Create Cart Reducer:

export default function AddToCartReducer(stateaction) {
}

Reducer accepts two parameters state and action. State holds the previous information and in the action we get the values that are being passed.

export default function AddToCartReducer(stateaction) {
  if (action.type === 'addedtoCart') {
 let { idimagetitledescriptionpricequantity } = action.payload;       
 let TotalPrice = (parseInt(price* parseInt(quantity));
 let cartProduct = {id: id + title,title,image,description,price,totalPrice:TotalPrice,quantity}
 let totalItems = state.totalItems + quantity;
  return {
          ...state
          cart: [...state.cart,cartProduct],
          totalItems: totalItems
          };    
       }
}

In the above code action.type tells code what to do if the action.type matches to any of the conditions or cases. In this case if the action.type===’AddedToCart’  code will update the cart.
Note: It is suggested by react to use switch cases instead of if condition.

Step 5: Components

In the ProductDetails component, include a button that triggers an onClick event:

 <button className="add-to-cart-button"
 onClick={() =>
   AddToCart(ProductDescription[0].id,
   ProductDescription[0].image,
   ProductDescription[0].title,
   ProductDescription[0].description,
   ProductDescription[0].price,
   ItemQuantity)}>
   Add to Cart                   
 button>

Don’t forget to import the context:

import { useCartContext } from '../contexts/CartContext';

And call ‘AddToCart’ function from the ‘useCartContext’:

 const { AddToCart } = useCartContext();

These steps are crucial for setting up the Add to Cart functionality in the ‘ProductDetails’ Page


Step 6: Integration in index.js

In index.js, import and wrap the App component with CartProvider 

import React from 'react';import ReactDOM from 'react-dom/client';
import './index.css';import App from './App';
import reportWebVitals from './reportWebVitals';
import { CartProvider } from './contexts/CartContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render  <React.StrictMode> 
    <CartProvider>      
      <App />    
    CartProvider>  
  React.StrictMode>
 ); 
reportWebVitals();

Now, the Cart values are accessible anywhere within the components by importing and using useCartContext:

import { useCartContext } from '../contexts/CartContext';

Import  useCartContext from CartContext and within the function component get cart

 const { Cart } = useCartContext();

Conclusion

In this blog, we've explored the use of ReactJS context and reducer hooks to implement an Add to Cart functionality. By leveraging these hooks, we can efficiently manage state and avoid prop drilling, leading to a more organized and scalable codebase. Feel free to explore additional features and functionalities to enhance your React applications.

Source Code


React Js Add To Cart Source Code

Asad Ibrahim Contact


Muhammad Asad Ibrahim

Pakistan

Upvotes: 26


Thanks for the detailed explanation

Anonymous (0 Upvotes)
Reply

To the point, great explanation.

Anonymous (0 Upvotes)
Reply

Finally a good post. Thanks for this stuff

Anonymous (0 Upvotes)
Reply

You can find YouTube videos related to these topic but hard to find articles explained this well. Great job 👍

Anonymous (0 Upvotes)
Reply

Great job 👏

Anonymous (0 Upvotes)
Reply

Great 👍

Anonymous (0 Upvotes)
Reply

Good 👍

Anonymous (0 Upvotes)
Reply

This article helped me out in understanding and implementing the hooks. Thanks for this detailed article.

Anonymous (0 Upvotes)
Reply

Great explanation 💯

Anonymous (0 Upvotes)
Reply
0/2000