Skip to main content

Overview

The useProducts hook is a React Query wrapper that fetches all products from the e-commerce API. It handles caching, loading states, and automatic refetching. Source: src/hooks/useProducts.js:5

Function Signature

export const useProducts = () => {
  return useQuery({
    queryKey: ["products"],
    queryFn: productService.getAll,
  });
};

Parameters

This hook takes no parameters.

Return Value

Returns a React Query result object with the following properties:
data
object
Product data returned from the API
products
array
Array of product objects (up to 200 products)
isLoading
boolean
true when the initial data is being fetched
isError
boolean
true if an error occurred during fetching
error
Error | null
Error object if the request failed
refetch
function
Function to manually refetch the products data

Usage Example

import { useProducts } from "../hooks/useProducts";
import ProductCard from "../components/productCard/ProductCard";
import SkeletonCard from "../components/SkeletonCard";

export const Home = () => {
  const {
    data: productsData,
    isLoading,
    isError,
    error,
    refetch,
  } = useProducts();

  const products = productsData?.products || [];

  if (isLoading) {
    return (
      <div className="row g-4">
        {Array.from({ length: 12 }).map((_, index) => (
          <SkeletonCard key={index} />
        ))}
      </div>
    );
  }

  if (isError) {
    return (
      <div className="alert text-center">
        <h5>⚠️ Error loading products</h5>
        <p>{error?.message || "Something went wrong."}</p>
        <button onClick={() => refetch()}>Try Again</button>
      </div>
    );
  }

  return (
    <div className="row g-4">
      {products.map((product) => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  );
};

API Service

The hook uses productService.getAll() which makes a GET request to /products?limit=200. Source: src/services/productService.js:4

Caching

Products are cached with the query key ["products"]. React Query automatically:
  • Caches the response
  • Deduplicates requests
  • Refetches stale data in the background
  • Shares data across components

useProductsByCategory

The same file also exports useProductsByCategory for fetching products filtered by category:
export const useProductsByCategory = (category) => {
  return useQuery({
    queryKey: ["products", "category", category],
    queryFn: () => productService.getByCategory(category),
    enabled: !!category,
  });
};

Parameters

category
string
required
The category slug to filter products by

Behavior

The query is disabled when category is empty or undefined (via enabled: !!category)

Build docs developers (and LLMs) love