Next.js Discord

Discord Forum

Too many rerenders when using useContext()

Unanswered
Rhinelander posted this in #help-forum
Open in Discord
RhinelanderOP
Just context for my cart to store the items, but it causes too many rerenders but don't know what to change to fix that

"use client";
import type { CartProduct } from "@/types/product";
import { createContext, useCallback, useContext, useState } from "react";

export interface CartContextProps {
  products: CartProduct[];
  addProduct: (product: CartProduct) => void;
}

const CartContext = createContext<CartContextProps | undefined>(undefined);

export function CartWrapper({ children }: { children: React.ReactNode }) {
  const [products, setProducts] = useState<CartProduct[]>([]);

  const addProduct = useCallback((newProduct: CartProduct) => {
    setProducts((prevProducts) => {
      const existingProductIndex = prevProducts.findIndex(
        (product) => product.id === newProduct.id,
      );
      if (existingProductIndex > -1) {
        const updatedProducts = [...prevProducts];
        updatedProducts[existingProductIndex].quantity += newProduct.quantity;
        return updatedProducts;
      } else {
        return [...prevProducts, newProduct];
      }
    });
  }, []);

  return (
    <CartContext.Provider value={{ products, addProduct }}>
      {children}
    </CartContext.Provider>
  );
}

export function useCartContext() {
  const context = useContext(CartContext);

  if (!context) {
    throw new Error("useCartContext must be used within a CartWrapper");
  }

  return context;
}


This is the problem
// the rest of the code...

  const handleAddToCart = () => {
    addProduct(newProduct); // This is the problematic part
    console.log(newProduct); // This outputs the desired object
  };

  return (
    <Button
      onClick={handleAddToCart}
      className={cn("flex gap-x-3", className)}
      disabled={!stock}
    >
   ...
    </Button>
  );
};

export default AddToCartBtn;

0 Replies