Skip to main content

Overview

The useCategories hook is a React Query wrapper that fetches all available product categories from the API. It provides category data for filtering and navigation. Source: src/hooks/useCategories.js:4

Function Signature

export const useCategories = () => {
  return useQuery({
    queryKey: ["categories"],
    queryFn: categoryService.getAll,
  });
};

Parameters

This hook takes no parameters.

Return Value

Returns a React Query result object:
data
array
Array of category objects. Each category contains:
slug
string
Unique identifier for the category (e.g., "electronics", "clothing")
name
string
Display name of the category
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

Usage Example

import { useCategories } from "../hooks/useCategories";
import Filters from "../components/filters/Filters";

export const Home = () => {
  const { data: categories = [] } = useCategories();

  return (
    <div className="container py-5">
      <h2 className="mb-4">Store</h2>
      
      <Filters
        categories={categories}
        // ... other props
      />
    </div>
  );
};

Default Value Pattern

Notice the destructuring pattern { data: categories = [] } - this provides an empty array as the default value when data is still loading or undefined, preventing runtime errors when mapping over categories.
// Recommended pattern
const { data: categories = [] } = useCategories();

// Now safe to use immediately
categories.map(cat => ...)

API Service

The hook uses categoryService.getAll() which fetches categories from the API endpoint. Source: src/services/categoryService.js

Caching

Categories are cached with the query key ["categories"]. Since categories rarely change, this data is efficiently shared across all components that need it.

Real-World Example

From the Filters component (src/components/filters/Filters.jsx:112):
{categories.map((cat) => (
  <button
    key={cat.slug}
    className={`filters-category-chip ${category === cat.slug ? "active" : ""}`}
    onClick={() => handleCategoryChange(cat.slug)}
  >
    {cat.name}
  </button>
))}

Build docs developers (and LLMs) love