Can useReducer be used for state management instead of useState?

I have a set of product details stored in in Firestore. I’ve created a custom hook to fetch the product details. The product categories should be displayed in the matching url param. As I add more product categories to be displayed in other urls, the product cards don’t render on mount. When I try to edit the productcard component, the product card renders and disappears in seconds. The data is being fetched correctly and is being rendered properly, but the rendered product card disappears in seconds. I’m unable to figure what the issue is as there’s no error in the console. Could it be anything related to state management?

//The custom hook for fetching product details

import { db } from "../../firebaseConfig";
import { collection, getDocs } from "firebase/firestore";
import { useState, useEffect } from "react";

interface ProductDetails {
  name: string;
  imageURLs: string[];
  rating: number;
  reviewsCount: number;
  monthlySalesCount: number;
  isBestseller: boolean;
  listPrice: number;
  discount: number;
  shippingPrice: number;
  Color: string[]; 
  productDescription: string[];
  dateFirstAvailable: Date;
}

interface Data {
  id: string;
  data: ProductDetails[];
}

const useProductDetails = () => {
  const [productDetails, setProductDetails] = useState<Data[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchProductDetails = async () => {
      try {
        // Fetch all categories from the products collection.
        const productCategories = collection(db, "products");
        const productDocumentsSnapshot = await getDocs(productCategories);

        // An array to store product details
        const productsData: Data[] = [];

        // Iterate over each document in the products collection.
        for (const productDoc of productDocumentsSnapshot.docs) {
          const productId = productDoc.id;
          // For each product category, fetch all documents from the productslist subcollection.
          const productListCollection = collection(
            db,
            `products/${productId}/productslist`
          );
          const productsListSnapshot = await getDocs(productListCollection);
          // Map over the documents in productslist to extract ProductDetails data.
          const productDetails: ProductDetails[] =
            productsListSnapshot.docs.map(
              (detailDoc) => detailDoc.data() as ProductDetails
            );

          // Push an object with id and data to productsData.
          productsData.push({
            id: productId,
            data: productDetails,
          });

          // Update the productDetails state with the fetched data.
          setProductDetails(productsData);
          console.log("Updated products state:", productsData);
        }
      } catch (error) {
        console.error("Error fetching products:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchProductDetails();
  }, []);

  return { loading, productDetails };
};

export default useProductDetails;



//The code for rendering the product card

import StarRating from "../sidebar/StarRating";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import useProductDetails from "../../useProductDetails";
import RenderColourOptions from "../../RenderColourOptions";
import { Link } from "react-router-dom";
import useFetchCountry from "../../../useFetchCountry";

interface ProductListProps {
  id: string | undefined;
}

function ProductCard(props: ProductListProps) {
  const { loading, productDetails } = useProductDetails();
  const { country } = useFetchCountry();

  if (loading) {
    return <p>Loading...</p>;
  }

  const calculateDiscountedPrice = (
    listPrice: number,
    discount: number
  ): string => {
    const discountedPrice = (listPrice - listPrice * (discount / 100)).toFixed(
      2
    );
    return discountedPrice;
  };

  const renderFormattedPrice = (price: string | number) => {
    const priceString = typeof price === "number" ? price.toString() : price;
    const [wholeNumber, fractional] = priceString.split(".");

    return (
      <>
        <span className="text-clamp16 ">{wholeNumber}</span>
        {fractional === "00" ? null : (
          <sup>
            <span className="text-clamp6 align-super">{fractional}</span>
          </sup>
        )}
      </>
    );
  };

  const formatSalesCount = (num: number) => {
    if (num >= 1000) {
      const formattedSalesCount = new Intl.NumberFormat("en-US", {
        notation: "compact",
      }).format(num);
      return `${formattedSalesCount}+`;
    } else return num;
  };

  const calculateDeliveryDate = () => {
    const currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + 20);

    return currentDate.toLocaleString("en-US", {
      weekday: "short",
      month: "short",
      day: "numeric",
    });
  };

  return (
    <>
      {productDetails.map((product) => {
        if (product.id === props.id) {
          return product.data.map((details) => (
            <div
              key={product.id}
              className="mr-[1%] mb-[1%] flex border-[1px] border-gray-100 rounded-[6px]"
            >
              <div className="bg-gray-100 w-[25%] rounded-l-[4px]">
                <img
                  src={details.imageURLs[0]}
                  alt={details.name}
                  className="mix-blend-multiply py-[15%] px-[5%]"
                  key={details.name}
                />
              </div>
              <div className="bg-white w-[75%] rounded-r-[4px] pl-[1.5%]">
                <Link to="">
                  <h1 className="text-clamp15 my-[0.75%] line-clamp-2">
                    {details.name}
                  </h1>
                </Link>
                <div className="flex items-center -mt-[0.75%]">
                  <StarRating
                    rating={details.rating}
                    fontSize="clamp(0.5625rem, 0.2984rem + 1.1268vi, 1.3125rem)"
                  />
                  <KeyboardArrowDownIcon
                    style={{
                      fontSize:
                        "clamp(0.375rem, 0.1109rem + 1.1268vi, 1.125rem)",
                    }}
                    className="-ml-[1.75%] text-gray-400"
                  />
                  <p className="text-clamp11 text-cyan-800 font-sans">
                    {details.reviewsCount.toLocaleString()}
                  </p>
                </div>
                <p className="text-clamp13 text-gray-700 mb-[1%]">{`${formatSalesCount(
                  details.monthlySalesCount
                )} bought in past month`}</p>
                <div className="flex items-baseline">
                  <p>
                    {details.discount ? (
                      <>
                        <sup>
                          <span className="text-clamp10 align-super">$</span>
                        </sup>
                        {renderFormattedPrice(
                          calculateDiscountedPrice(
                            details.listPrice,
                            details.discount
                          )
                        )}
                      </>
                    ) : (
                      <>
                        <sup>
                          <span className="text-clamp10 align-super">$</span>
                        </sup>
                        {renderFormattedPrice(details.listPrice)}
                      </>
                    )}
                  </p>

                  {details.discount ? (
                    <p className=" text-clamp13 text-gray-700 ml-[1%]">
                      List:
                      <span className="line-through ml-[5%]">
                        ${details.listPrice}
                      </span>
                    </p>
                  ) : null}
                </div>
                <p className="mt-[1%] text-clamp13">
                  Delivery{"  "}
                  <span className="font-bold tracking-wide">
                    {calculateDeliveryDate()}
                  </span>
                </p>
                <p className="text-clamp1 mt-[0.5%]">Ships to {country}</p>
                <button className="bg-yellow-400 px-[1.75%] py-[0.5%] mt-[1%] rounded-[25px] text-clamp10">
                  Add to cart
                </button>
                <RenderColourOptions colors={details.Color} />
              </div>
            </div>
          ));
        }
        return null;
      })}
    </>
  );
}

export default ProductCard;

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật