<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ React.memo - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ React.memo - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 26 Jul 2026 11:16:16 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/reactmemo/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Avoid Overusing useCallback and useMemo in React ]]>
                </title>
                <description>
                    <![CDATA[ If you've spent enough time in the React ecosystem, you'll have likely seen codebases where nearly every function is wrapped with useCallback and the computed value is wrapped with useMemo. The reason ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-avoid-overusing-usecallback-and-usememo-in-react/</link>
                <guid isPermaLink="false">6a32f4091d5034aa7d96e448</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Performance Optimization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Memoization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React.memo ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Olaleye Blessing ]]>
                </dc:creator>
                <pubDate>Wed, 17 Jun 2026 19:22:49 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/88ac6adf-ef3d-4f28-9dac-22ea12ed5005.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've spent enough time in the React ecosystem, you'll have likely seen codebases where nearly every function is wrapped with <code>useCallback</code> and the computed value is wrapped with <code>useMemo</code>.</p>
<p>The reason behind this is “memoization equals better performance”. But most of the time, this doesn’t really translate to better performance, and it often produces code that's harder to debug.</p>
<p>In this article, you'll learn how to structure your code to avoid overusing <code>useCallback</code> and <code>useMemo</code>.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>You should be comfortable with React hooks and components before reading this tutorial. Familiarity with <code>useState</code>, <code>useEffect</code>, and <code>useRef</code> is assumed. You can read the following freeCodeCamp articles if you need a refresher on <code>useCallback</code> and <code>useMemo</code>:</p>
<ul>
<li><p><a href="https://www.freecodecamp.org/news/caching-in-react/">How to Use the useMemo and useCallback Hooks</a></p>
</li>
<li><p><a href="https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/">Difference between the useMemo and useCallback Hooks</a></p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-what-usecallback-and-usememo-do">What useCallback and useMemo Do</a></p>
<ul>
<li><p><a href="#heading-usememo">useMemo</a></p>
</li>
<li><p><a href="#heading-usecallback">useCallback</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-problem-with-memoization">Problem With Memoization</a></p>
</li>
<li><p><a href="#heading-the-problematic-page">The Problematic Page</a></p>
<ul>
<li><p><a href="#heading-how-to-move-state-down">How to Move State Down</a></p>
<ul>
<li><p><a href="#heading-move-producttable-logic-to-its-component">Move ProductTable Logic To Its Component</a></p>
</li>
<li><p><a href="#heading-move-filtering-logic-to-its-component">Move Filtering Logic To Its Component</a></p>
</li>
<li><p><a href="#heading-move-search-logic-into-its-component">Move Search Logic Into Its Component</a></p>
</li>
<li><p><a href="#heading-move-filter-chips-into-its-component">Move Filter Chips into Its Component</a></p>
</li>
<li><p><a href="#heading-the-final-searchpage">The Final SearchPage</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-fix-your-code-before-reaching-for-these-hooks">Fix Your Code Before Reaching For These Hooks</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-when-to-use-usecallback-and-usememo">When to Use useCallback and useMemo</a></p>
<ul>
<li><p><a href="#heading-measure-before-you-optimize">Measure Before You Optimize</a></p>
</li>
<li><p><a href="#heading-stabilize-references-for-reactmemo-children">Stabilize References for React.memo Children</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-usecallback-and-usememo-do">What <code>useCallback</code> and <code>useMemo</code> Do</h2>
<p>Before moving to how to avoid overusing them, we'll look briefly at what these hooks do.</p>
<h3 id="heading-usememo">useMemo</h3>
<p><code>useMemo</code> caches the return value of a function between re-renders. Imagine you have a sorted list of items in a component:</p>
<pre><code class="language-typescript">interface Item {
  name: string;
  createdAt: string;
}

function App() {
  // == some other states ==
  // == some other states ==
  const [items, setItems] = useState&lt;Item[]&gt;([]);

  const sortedItems = [...items].sort(
    (a, b) =&gt; new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
  );

  return (
    &lt;&gt;
      &lt;ul&gt;
        {sortedItems.map((i) =&gt; (
          &lt;li key={i.name}&gt;{i.name}&lt;/li&gt;
        ))}
      &lt;/ul&gt;
    &lt;/&gt;
  );
}
</code></pre>
<p>React recomputes <code>sortedItems</code> every time the <code>App</code> component re-renders. This means <code>sortedItems</code> will be recalculated anytime there are any state changes in the <code>App</code> component.</p>
<p>React developers often use <code>useMemo</code> to cache values like this.</p>
<p>Wrapping it with <code>useMemo</code> ensures that <code>sortedItems</code> is only calculated when <code>items</code> actually changes:</p>
<pre><code class="language-typescript">const sortedItems = useMemo(() =&gt; {
  return [...items].sort(
    (a, b) =&gt; new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
  );
}, [items]);
</code></pre>
<h3 id="heading-usecallback">useCallback</h3>
<p><code>useCallback</code> caches the function itself. The function below will be recreated every time some states in the component change:</p>
<pre><code class="language-typescript">function App() {
  // == some other states ==
  // == some other states ==
  const [userId, setUserId] = useState(0);

  const verifyUser = async () =&gt; {
    // update a state to show loading
    console.log("__ Do something with user id __", userId);
    // update a state to remove loading
  };

  return (
    &lt;&gt;
      &lt;button onClick={verifyUser}&gt;Verify&lt;/button&gt;
    &lt;/&gt;
  );
}
</code></pre>
<p>Wrapping it with <code>useCallback</code> keeps the same function reference as long as <code>userId</code> hasn’t changed:</p>
<pre><code class="language-typescript">function App() {
  // == some other states ==
  // == some other states ==
  const [userId, setUserId] = useState(0);

  const verifyUser = useCallback(async () =&gt; {
    // update a state to show loading
    console.log("__ Do something with user id __", userId);
    // update a state to remove loading
  }, [userId]);

  return (
    &lt;&gt;
      &lt;button onClick={verifyUser}&gt;Verify&lt;/button&gt;
    &lt;/&gt;
  );
}
</code></pre>
<h2 id="heading-problem-with-memoization">Problem With Memoization</h2>
<p>Nothing is free in life, and memoization is no exception. Every time you use <code>useCallback</code> or <code>useMemo</code>:</p>
<ul>
<li><p>Your app allocates memory to store the cached value and dependency array.</p>
</li>
<li><p>Your component runs a comparison to check if the dependencies have changed</p>
</li>
</ul>
<p>This memoization isn't useful most of the time. Creating a JavaScript function is cheap. Sorting a list of 50 items is cheap. Wrapping these in a memoization hook adds more cost than it prevents. (But keep in mind that if profiling shows sorting is a bottleneck, <code>useMemo</code> is still reasonable there.)</p>
<p>The better approach is to structure your components so that re-renders are less frequent.</p>
<h2 id="heading-the-problematic-page">The Problematic Page</h2>
<p>To see this in action, you'll go through a search page where a parent component manages all the state and logic for the entire page.</p>
<p>To code along, you can clone a simple Next.js project I set up for this:</p>
<pre><code class="language-shell">git clone https://github.com/Olaleye-Blessing/freecodecamp-usecallback-usememo.git

# navigate to the folder
cd freecodecamp-usecallback-usememo

# install the packages
pnpm install

# start development
pnpm dev
</code></pre>
<p>The search page consists of the following:</p>
<ul>
<li><p><a href="https://github.com/Olaleye-Blessing/freecodecamp-avoid-overusing-memoization/blob/main/app/_components/header.tsx">A Header</a> that shows the title of the page.</p>
</li>
<li><p><a href="https://github.com/Olaleye-Blessing/freecodecamp-avoid-overusing-memoization/blob/main/app/_components/search.tsx">A Search field</a> that allows user to search for the name of a product</p>
</li>
<li><p><a href="https://github.com/Olaleye-Blessing/freecodecamp-avoid-overusing-memoization/blob/0d3f5eb7fadc88e8608d0965daf01148c2a35f83/app/_components/header.tsx#L49">A Filter button</a> that opens a drawer for more filtering.</p>
</li>
<li><p><a href="https://github.com/Olaleye-Blessing/freecodecamp-avoid-overusing-memoization/blob/main/app/_components/filter-drawer.tsx">A Drawer</a> for filtering by country, color, mode, and/or price range.</p>
</li>
<li><p><a href="https://github.com/Olaleye-Blessing/freecodecamp-avoid-overusing-memoization/blob/main/app/_components/products-table.tsx">A Product table</a> that shows the search result</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/629122ced97f80b5091d8058/423d6239-2603-4b32-8fe9-080f28d136ad.gif" alt="A demo of the search page. The user searches for &quot;alpine&quot;, clears it, then applies filters in the drawer." style="display:block;margin:0 auto" width="800" height="477" loading="lazy">

<p>All the child components mentioned above maintain no states and functions. They all derive their states and functions from the <code>SearchPage</code> component.</p>
<p>We won’t be going through the child components. They only render the UIs. They have no logic whatsoever.</p>
<p>The <code>SearchPage</code> component looks like this:</p>
<pre><code class="language-typescript">"use client";

import { ChangeEvent, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  fetchColors,
  fetchCountries,
  fetchModes,
  fetchProducts,
} from "./utils";
import { Header } from "./_components/header";
import { FilterDrawer } from "./_components/filter-drawer";
import { ProductTable } from "./_components/products-table";
import { FilterChips } from "./_components/filter-chips";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { FilterState, LocalSortField, SortDir, SortField } from "./interfaces";

const DEFAULTS: FilterState = {
  query: "",
  country: "",
  color: "",
  mode: "",
  minPrice: "",
  maxPrice: "",
  sortField: "name",
  sortDir: "asc",
};

export default function SearchPage() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [drawerOpen, setDrawerOpen] = useState(false);

  const [localSort, setLocalSort] = useState&lt;{
    field: LocalSortField;
    dir: "asc" | "desc";
  } | null&gt;(null);

  const searchRef = useRef&lt;HTMLInputElement&gt;(null);
  const searchTimerRef = useRef&lt;ReturnType&lt;typeof setTimeout&gt; | null&gt;(null);

  const filters: FilterState = {
    query: searchParams.get("q") ?? DEFAULTS.query,
    country: searchParams.get("country") ?? DEFAULTS.country,
    color: searchParams.get("color") ?? DEFAULTS.color,
    mode: searchParams.get("mode") ?? DEFAULTS.mode,
    minPrice: searchParams.get("minPrice") ?? DEFAULTS.minPrice,
    maxPrice: searchParams.get("maxPrice") ?? DEFAULTS.maxPrice,
    sortField:
      (searchParams.get("sortField") as SortField) ?? DEFAULTS.sortField,
    sortDir: (searchParams.get("sortDir") as SortDir) ?? DEFAULTS.sortDir,
  };

  const apiFilters = {
    query: filters.query,
    country: filters.country || undefined,
    color: filters.color || undefined,
    mode: filters.mode || undefined,
    minPrice: filters.minPrice ? Number(filters.minPrice) : undefined,
    maxPrice: filters.maxPrice ? Number(filters.maxPrice) : undefined,
    sortField: filters.sortField,
    sortDir: filters.sortDir,
  };

  const productsQuery = useQuery({
    queryKey: ["products", apiFilters],
    queryFn: () =&gt; fetchProducts(apiFilters),
  });

  const countriesQuery = useQuery({
    queryKey: ["countries"],
    queryFn: fetchCountries,
    staleTime: Infinity,
  });

  const colorsQuery = useQuery({
    queryKey: ["colors"],
    queryFn: fetchColors,
    staleTime: Infinity,
  });

  const modesQuery = useQuery({
    queryKey: ["modes"],
    queryFn: fetchModes,
    staleTime: Infinity,
  });

  // Updates the filter in the drawer
  const setFilters = (partial: Partial&lt;FilterState&gt;) =&gt; {
    const next = new URLSearchParams(searchParams.toString());
    const merged = { ...filters, ...partial };

    const keyMap: Record&lt;keyof FilterState, string&gt; = {
      query: "q",
      country: "country",
      color: "color",
      mode: "mode",
      minPrice: "minPrice",
      maxPrice: "maxPrice",
      sortField: "sortField",
      sortDir: "sortDir",
    };

    (Object.keys(merged) as (keyof FilterState)[]).forEach((k) =&gt; {
      const paramKey = keyMap[k];
      const val = merged[k];
      const def = DEFAULTS[k];
      if (val &amp;&amp; val !== def) {
        next.set(paramKey, val);
      } else {
        next.delete(paramKey);
      }
    });

    router.push(`\({pathname}?\){next.toString()}`, { scroll: false });
  };

  const resetFilters = () =&gt; {
    router.push(pathname, { scroll: false });
  };

  const handleQueryChange = (e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {
    const val = e.target.value;

    if (searchTimerRef.current) clearTimeout(searchTimerRef.current);

    searchTimerRef.current = setTimeout(() =&gt; {
      setFilters({ query: val });
    }, 400);
  };

  const handleClearQuery = () =&gt; {
    if (searchRef.current) {
      searchRef.current.value = "";
    }

    setFilters({ query: "" });
  };

  const handleColumnClick = (field: LocalSortField) =&gt; {
    setLocalSort((prev) =&gt; {
      if (!prev || prev.field !== field) return { field, dir: "asc" };

      if (prev.dir === "asc") return { field, dir: "desc" };

      return null;
    });
  };

  const hasPriceFilter = filters.minPrice || filters.maxPrice;
  const priceLabel = [
    filters.minPrice ? `$${filters.minPrice}` : null,
    filters.maxPrice ? `$${filters.maxPrice}` : null,
  ]
    .filter(Boolean)
    .join(" - ");

  const activeFilterCount = [
    filters.country,
    filters.color,
    filters.mode,
    filters.minPrice,
    filters.maxPrice,
  ].filter(Boolean).length;

  let sortedProducts = [...(productsQuery.data || [])];
  if (localSort) {
    sortedProducts = [...sortedProducts].sort((a, b) =&gt; {
      const aVal = a[localSort.field];
      const bVal = b[localSort.field];
      const cmp =
        typeof aVal === "string"
          ? aVal.localeCompare(bVal as string)
          : (aVal as number) - (bVal as number);
      return localSort.dir === "desc" ? -cmp : cmp;
    });
  }

  useEffect(() =&gt; {
    return () =&gt; {
      if (searchTimerRef.current) clearTimeout(searchTimerRef.current);
    };
  }, []);

  return (
    &lt;div className="min-h-screen bg-stone-50"&gt;
      &lt;Header
        query={filters.query}
        handleClearQuery={handleClearQuery}
        onToggleFilters={() =&gt; setDrawerOpen((v) =&gt; !v)}
        activeFilterCount={activeFilterCount}
        searchRef={searchRef}
        handleChange={handleQueryChange}
      /&gt;

      &lt;FilterDrawer
        open={drawerOpen}
        onClose={() =&gt; setDrawerOpen(false)}
        filters={filters}
        onChange={setFilters}
        onReset={resetFilters}
        countries={countriesQuery.data ?? []}
        colors={colorsQuery.data ?? []}
        modes={modesQuery.data ?? []}
        activeFilterCount={activeFilterCount}
      /&gt;

      &lt;main className="max-w-6xl mx-auto px-4 py-6"&gt;
        {activeFilterCount &gt; 0 &amp;&amp; (
          &lt;FilterChips
            filters={filters}
            setFilters={setFilters}
            hasPriceFilter={hasPriceFilter}
            priceLabel={priceLabel}
            resetFilters={resetFilters}
          /&gt;
        )}

        &lt;ProductTable
          products={sortedProducts}
          isLoading={productsQuery.isLoading}
          handleColumnClick={handleColumnClick}
          localSort={localSort}
        /&gt;
      &lt;/main&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The <code>SearchPage</code> component keeps track of all the logic needed to render the page:</p>
<ul>
<li><p>It fetches the <code>products</code>, <code>countries</code>, <code>colors</code>, and <code>modes</code>. It passes the <code>countries</code>, <code>colors</code> and <code>modes</code> to the drawer component</p>
</li>
<li><p>It keeps track of the drawer state.</p>
</li>
<li><p>It defines the functions needed to sort the product locally, and so on.</p>
</li>
</ul>
<p>The problem here is that a change in any of the states will lead to recreating all the functions in <code>SearchPage</code> component. For example, when <code>isLoading</code> in the <code>useQuery</code> of products (<code>productsQuery</code>) changes from <code>false</code> to <code>true</code>, all our functions and derived values will be recreated.</p>
<p>The first thing that might come to mind is caching functions and derived values using <code>useCallback</code> and <code>useMemo</code>. While this will work, it will add unnecessary performance overhead to this page.</p>
<p>A better solution is to move state and logic closer to where they are actually used.</p>
<h3 id="heading-how-to-move-state-down">How to Move State Down</h3>
<p>The idea is this: if only one component needs a piece of state or a function, that component should own it. When a child component manages its own state, changes to that state don't re-render the parent. This means all the sibling components’ states and functions stay stable without any memoization.</p>
<p>That said, don’t move logic so far down that shared behavior becomes harder to test or coordinate. The goal isn't to hide every piece of logic inside the deepest possible component. The goal is to place state and logic at the lowest level where they still make sense for the feature.</p>
<h4 id="heading-move-producttable-logic-to-its-component">Move ProductTable Logic to Its Component</h4>
<p>Looking at how products are fetched and sorted, you'll notice that the only component that uses this data is <code>ProductsTable</code>. This means we can move the fetching and sorting logic to the <code>ProductsTable</code>.</p>
<p>The <code>ProductsComponent</code> currently receives its states and logic as props:</p>
<pre><code class="language-typescript">"use client";

interface ProductTableProps {
  products: Product[];
  isLoading: boolean;
  handleColumnClick: (field: LocalSortField) =&gt; void;
  localSort: { field: LocalSortField; dir: SortDir } | null;
}

export function ProductTable({
  products,
  isLoading,
  handleColumnClick,
  localSort,
}: ProductTableProps) {
  // renders the UI using the props
}
</code></pre>
<p>Now, <code>ProductTable</code> will fetch and manage its logic:</p>
<pre><code class="language-typescript">interface ProductTableProps {
  filters: FilterState;
}

export function ProductTable({ filters }: ProductTableProps) {
  const [localSort, setLocalSort] = useState&lt;{
    field: LocalSortField;
    dir: "asc" | "desc";
  } | null&gt;(null);

  const apiFilters = {
    query: filters.query,
    country: filters.country || undefined,
    color: filters.color || undefined,
    mode: filters.mode || undefined,
    minPrice: filters.minPrice ? Number(filters.minPrice) : undefined,
    maxPrice: filters.maxPrice ? Number(filters.maxPrice) : undefined,
    sortField: filters.sortField,
    sortDir: filters.sortDir,
  };

  const { data: products = [], isLoading } = useQuery({
    queryKey: ["products", apiFilters],
    queryFn: () =&gt; fetchProducts(apiFilters),
  });

  const handleColumnClick = (field: LocalSortField) =&gt; {
    setLocalSort((prev) =&gt; {
      if (!prev || prev.field !== field) return { field, dir: "asc" };
      if (prev.dir === "asc") return { field, dir: "desc" };

      return null;
    });
  };

  let sortedProducts = products;
  if (localSort) {
    sortedProducts = [...products].sort((a, b) =&gt; {
      const aVal = a[localSort.field];
      const bVal = b[localSort.field];
      const cmp =
        typeof aVal === "string"
          ? aVal.localeCompare(bVal as string)
          : (aVal as number) - (bVal as number);
      return localSort.dir === "desc" ? -cmp : cmp;
    });
  }

  return &lt;&gt;{/*== renders the UI using the props ==*/}&lt;/&gt;;
}
</code></pre>
<p>Now when <code>isLoading</code> changes, the <code>SearchPage</code> component won’t re-render. This means the derived values and other functions in the <code>SearchPage</code> component won’t be recreated. The only value and function that will be recreated here are the <code>sortedProducts</code> and <code>handleColumnClick</code>.</p>
<p>The <code>SearchPage</code> component becomes this:</p>
<pre><code class="language-typescript">"use client";

import { ChangeEvent, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchColors, fetchCountries, fetchModes } from "./utils";
import { Header } from "./_components/header";
import { FilterDrawer } from "./_components/filter-drawer";
import { ProductTable } from "./_components/products-table";
import { FilterChips } from "./_components/filter-chips";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { FilterState, SortDir, SortField } from "./interfaces";

const DEFAULTS: FilterState = {
  query: "",
  country: "",
  color: "",
  mode: "",
  minPrice: "",
  maxPrice: "",
  sortField: "name",
  sortDir: "asc",
};

export default function SearchPage() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [drawerOpen, setDrawerOpen] = useState(false);

  const searchRef = useRef&lt;HTMLInputElement&gt;(null);
  const searchTimerRef = useRef&lt;ReturnType&lt;typeof setTimeout&gt; | null&gt;(null);

  const filters: FilterState = {
    query: searchParams.get("q") ?? DEFAULTS.query,
    country: searchParams.get("country") ?? DEFAULTS.country,
    color: searchParams.get("color") ?? DEFAULTS.color,
    mode: searchParams.get("mode") ?? DEFAULTS.mode,
    minPrice: searchParams.get("minPrice") ?? DEFAULTS.minPrice,
    maxPrice: searchParams.get("maxPrice") ?? DEFAULTS.maxPrice,
    sortField:
      (searchParams.get("sortField") as SortField) ?? DEFAULTS.sortField,
    sortDir: (searchParams.get("sortDir") as SortDir) ?? DEFAULTS.sortDir,
  };

  const countriesQuery = useQuery({
    queryKey: ["countries"],
    queryFn: fetchCountries,
    staleTime: Infinity,
  });

  const colorsQuery = useQuery({
    queryKey: ["colors"],
    queryFn: fetchColors,
    staleTime: Infinity,
  });

  const modesQuery = useQuery({
    queryKey: ["modes"],
    queryFn: fetchModes,
    staleTime: Infinity,
  });

  // Updates the filter in the drawer
  const setFilters = (partial: Partial&lt;FilterState&gt;) =&gt; {
    const next = new URLSearchParams(searchParams.toString());
    const merged = { ...filters, ...partial };

    const keyMap: Record&lt;keyof FilterState, string&gt; = {
      query: "q",
      country: "country",
      color: "color",
      mode: "mode",
      minPrice: "minPrice",
      maxPrice: "maxPrice",
      sortField: "sortField",
      sortDir: "sortDir",
    };

    (Object.keys(merged) as (keyof FilterState)[]).forEach((k) =&gt; {
      const paramKey = keyMap[k];
      const val = merged[k];
      const def = DEFAULTS[k];
      if (val &amp;&amp; val !== def) {
        next.set(paramKey, val);
      } else {
        next.delete(paramKey);
      }
    });

    router.push(`\({pathname}?\){next.toString()}`, { scroll: false });
  };

  const resetFilters = () =&gt; {
    router.push(pathname, { scroll: false });
  };

  const handleQueryChange = (e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {
    const val = e.target.value;

    if (searchTimerRef.current) clearTimeout(searchTimerRef.current);

    searchTimerRef.current = setTimeout(() =&gt; {
      setFilters({ query: val });
    }, 400);
  };

  const handleClearQuery = () =&gt; {
    if (searchRef.current) {
      searchRef.current.value = "";
    }

    setFilters({ query: "" });
  };

  const hasPriceFilter = filters.minPrice || filters.maxPrice;
  const priceLabel = [
    filters.minPrice ? `$${filters.minPrice}` : null,
    filters.maxPrice ? `$${filters.maxPrice}` : null,
  ]
    .filter(Boolean)
    .join(" - ");

  const activeFilterCount = [
    filters.country,
    filters.color,
    filters.mode,
    filters.minPrice,
    filters.maxPrice,
  ].filter(Boolean).length;

  useEffect(() =&gt; {
    return () =&gt; {
      if (searchTimerRef.current) clearTimeout(searchTimerRef.current);
    };
  }, []);

  return (
    &lt;div className="min-h-screen bg-stone-50"&gt;
      &lt;Header
        query={filters.query}
        onChange={setFilters}
        handleClearQuery={handleClearQuery}
        onToggleFilters={() =&gt; setDrawerOpen((v) =&gt; !v)}
        activeFilterCount={activeFilterCount}
        searchRef={searchRef}
        handleChange={handleQueryChange}
      /&gt;

      &lt;FilterDrawer
        open={drawerOpen}
        onClose={() =&gt; setDrawerOpen(false)}
        filters={filters}
        onChange={setFilters}
        onReset={resetFilters}
        countries={countriesQuery.data ?? []}
        colors={colorsQuery.data ?? []}
        modes={modesQuery.data ?? []}
        activeFilterCount={activeFilterCount}
      /&gt;

      &lt;main className="max-w-6xl mx-auto px-4 py-6"&gt;
        {activeFilterCount &gt; 0 &amp;&amp; (
          &lt;FilterChips
            filters={filters}
            setFilters={setFilters}
            hasPriceFilter={hasPriceFilter}
            priceLabel={priceLabel}
            resetFilters={resetFilters}
          /&gt;
        )}

        &lt;ProductTable filters={filters} /&gt;
      &lt;/main&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The <code>SearchPage</code> component no longer maintains fetching and sorting products data.</p>
<h4 id="heading-move-filtering-logic-to-its-component">Move Filtering Logic To Its Component</h4>
<p>We have different states, data, and functions to make this work:</p>
<ul>
<li><p><code>drawerOpen</code> and <code>setDrawerOpen</code> to control the filter drawer.</p>
</li>
<li><p><code>countries</code>, <code>colors</code> and <code>modes</code> data to allow user to select different options.</p>
</li>
<li><p><code>activeFilterCount</code> to show the number of active filters.</p>
</li>
</ul>
<p>There are two components for the filtering currently. First is a button inside the <code>Header</code> component that looks like this:</p>
<pre><code class="language-typescript">&lt;button
  onClick={onToggleFilters}
  className="relative ml-auto flex items-center gap-2 px-3 py-2 text-sm text-black font-medium border border-stone-300 rounded-lg hover:bg-stone-100 transition"
&gt;
  &lt;SlidersHorizontal className="w-4 h-4" /&gt;
  &lt;span className="hidden sm:inline"&gt;Filters&lt;/span&gt;
  {activeFilterCount &gt; 0 &amp;&amp; (
    &lt;span
      className="absolute -top-1.5 -right-1.5 flex items-center justify-center 
                             w-5 h-5 rounded-full bg-stone-900 text-white text-xs font-bold"
    &gt;
      {activeFilterCount}
    &lt;/span&gt;
  )}
&lt;/button&gt;;
</code></pre>
<p>Second is the <code>FilterDrawer</code> component that looks like this:</p>
<pre><code class="language-typescript">"use client";

import { useEffect, useRef } from "react";
import { X, RotateCcw } from "lucide-react";
import { FilterState } from "../interfaces";
import { SortSection } from "./filter/sort-section";
import { NarrowResultsSection } from "./filter/narrow-result-section";

interface FilterDrawerProps {
  open: boolean;
  onClose: () =&gt; void;
  filters: FilterState;
  onChange: (partial: Partial&lt;FilterState&gt;) =&gt; void;
  onReset: () =&gt; void;
  countries: string[];
  colors: string[];
  modes: string[];
  activeFilterCount: number;
}

export function FilterDrawer({
  open,
  onClose,
  filters,
  onChange,
  onReset,
  countries,
  colors,
  modes,
  activeFilterCount,
}: FilterDrawerProps) {
  const drawerRef = useRef&lt;HTMLDivElement&gt;(null);

  // Close on Escape
  useEffect(() =&gt; {
    const handler = (e: KeyboardEvent) =&gt; {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", handler);
    return () =&gt; document.removeEventListener("keydown", handler);
  }, [onClose]);

  // Prevent body scroll while open
  useEffect(() =&gt; {
    document.body.style.overflow = open ? "hidden" : "";
    return () =&gt; {
      document.body.style.overflow = "";
    };
  }, [open]);

  return (
    &lt;&gt;
      {/* Backdrop */}
      &lt;div
        className={`fixed inset-0 z-40 bg-black/30 transition-opacity duration-300 ${
          open
            ? "opacity-100 pointer-events-auto"
            : "opacity-0 pointer-events-none"
        }`}
        onClick={onClose}
      /&gt;

      {/* Drawer panel */}
      &lt;aside
        ref={drawerRef}
        className={`fixed top-0 right-0 z-50 h-full w-80 bg-white shadow-2xl 
                    flex flex-col transition-transform duration-300 ease-in-out
                    ${open ? "translate-x-0" : "translate-x-full"}`}
        aria-hidden={!open}
      &gt;
        {/* Header */}
        &lt;div className="flex items-center justify-between px-5 py-4 border-b border-stone-100"&gt;
          &lt;h2 className="font-semibold text-stone-900"&gt;
            Filters &amp;amp; Sort
            {activeFilterCount &gt; 0 &amp;&amp; (
              &lt;span className="ml-2 text-xs bg-stone-900 text-white px-1.5 py-0.5 rounded-full"&gt;
                {activeFilterCount}
              &lt;/span&gt;
            )}
          &lt;/h2&gt;
          &lt;button
            onClick={onClose}
            className="p-1.5 rounded-md hover:bg-stone-100 transition"
            aria-label="Close filters"
          &gt;
            &lt;X className="w-5 h-5 text-stone-600" /&gt;
          &lt;/button&gt;
        &lt;/div&gt;

        &lt;div className="flex-1 overflow-y-auto px-5 py-5 flex flex-col gap-6"&gt;
          &lt;SortSection
            sortField={filters.sortField}
            sortDir={filters.sortDir}
            onChange={onChange}
          /&gt;

          &lt;hr className="border-stone-100" /&gt;

          &lt;NarrowResultsSection
            filters={filters}
            onChange={onChange}
            countries={countries}
            colors={colors}
            modes={modes}
          /&gt;
        &lt;/div&gt;

        {/* Footer */}
        {activeFilterCount &gt; 0 &amp;&amp; (
          &lt;div className="px-5 py-4 border-t border-stone-100"&gt;
            &lt;button
              onClick={() =&gt; {
                onReset();
                onClose();
              }}
              className="w-full flex items-center justify-center gap-2 px-4 py-2.5 
                         border border-stone-300 rounded-lg text-sm font-medium 
                         hover:bg-stone-100 transition text-stone-700"
            &gt;
              &lt;RotateCcw className="w-4 h-4" /&gt;
              Clear all filters
            &lt;/button&gt;
          &lt;/div&gt;
        )}
      &lt;/aside&gt;
    &lt;/&gt;
  );
}
</code></pre>
<p>You can combine the 2 components into a single <code>Filter</code> component that owns all of this logic:</p>
<pre><code class="language-typescript">import { RotateCcw, SlidersHorizontal, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { SortSection } from "./filter/sort-section";
import { NarrowResultsSection } from "./filter/narrow-result-section";
import { FilterState } from "../interfaces";
import { usePathname, useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { fetchColors, fetchCountries, fetchModes } from "../utils";

interface FilterProps {
  filters: FilterState;
  onChange: (partial: Partial&lt;FilterState&gt;) =&gt; void;
}

const Filter = ({ filters, onChange }: FilterProps) =&gt; {
  const { data: countries = [] } = useQuery({
    queryKey: ["countries"],
    queryFn: fetchCountries,
    staleTime: Infinity,
  });

  const { data: colors = [] } = useQuery({
    queryKey: ["colors"],
    queryFn: fetchColors,
    staleTime: Infinity,
  });

  const { data: modes = [] } = useQuery({
    queryKey: ["modes"],
    queryFn: fetchModes,
    staleTime: Infinity,
  });

  const router = useRouter();
  const pathname = usePathname();
  const [drawerOpen, setDrawerOpen] = useState(false);

  const drawerRef = useRef&lt;HTMLDivElement&gt;(null);

  const onClose = () =&gt; setDrawerOpen(false);
  const openDrawer = () =&gt; setDrawerOpen(true);
  const resetFilters = () =&gt; {
    onClose();
    router.push(pathname, { scroll: false });
  };

  const activeFilterCount = [
    filters.country,
    filters.color,
    filters.mode,
    filters.minPrice,
    filters.maxPrice,
  ].filter(Boolean).length;

  // Close on Escape
  useEffect(() =&gt; {
    const handler = (e: KeyboardEvent) =&gt; {
      if (e.key === "Escape") setDrawerOpen(false);
    };
    document.addEventListener("keydown", handler);
    return () =&gt; document.removeEventListener("keydown", handler);
  }, []);

  // Prevent body scroll while open
  useEffect(() =&gt; {
    document.body.style.overflow = drawerOpen ? "hidden" : "";
    return () =&gt; {
      document.body.style.overflow = "";
    };
  }, [drawerOpen]);

  return (
    &lt;&gt;
      &lt;button
        onClick={openDrawer}
        className="relative ml-auto flex items-center gap-2 px-3 py-2 text-sm text-black font-medium border border-stone-300 rounded-lg hover:bg-stone-100 transition"
      &gt;
        &lt;SlidersHorizontal className="w-4 h-4" /&gt;
        &lt;span className="hidden sm:inline"&gt;Filters&lt;/span&gt;
        {activeFilterCount &gt; 0 &amp;&amp; (
          &lt;span
            className="absolute -top-1.5 -right-1.5 flex items-center justify-center 
                             w-5 h-5 rounded-full bg-stone-900 text-white text-xs font-bold"
          &gt;
            {activeFilterCount}
          &lt;/span&gt;
        )}
      &lt;/button&gt;
      {/* Backdrop */}
      &lt;div
        className={`fixed inset-0 z-40 bg-black/30 transition-opacity duration-300 ${
          drawerOpen
            ? "opacity-100 pointer-events-auto"
            : "opacity-0 pointer-events-none"
        }`}
        onClick={onClose}
      /&gt;

      {/* Drawer panel */}
      &lt;aside
        ref={drawerRef}
        className={`fixed top-0 right-0 z-50 h-full w-80 bg-white shadow-2xl 
                    flex flex-col transition-transform duration-300 ease-in-out
                    ${drawerOpen ? "translate-x-0" : "translate-x-full"}`}
        aria-hidden={!drawerOpen}
      &gt;
        {/* Header */}
        &lt;div className="flex items-center justify-between px-5 py-4 border-b border-stone-100"&gt;
          &lt;h2 className="font-semibold text-stone-900"&gt;
            Filters &amp;amp; Sort
            {activeFilterCount &gt; 0 &amp;&amp; (
              &lt;span className="ml-2 text-xs bg-stone-900 text-white px-1.5 py-0.5 rounded-full"&gt;
                {activeFilterCount}
              &lt;/span&gt;
            )}
          &lt;/h2&gt;
          &lt;button
            onClick={onClose}
            className="p-1.5 rounded-md hover:bg-stone-100 transition"
            aria-label="Close filters"
          &gt;
            &lt;X className="w-5 h-5 text-stone-600" /&gt;
          &lt;/button&gt;
        &lt;/div&gt;

        &lt;div className="flex-1 overflow-y-auto px-5 py-5 flex flex-col gap-6"&gt;
          &lt;SortSection
            sortField={filters.sortField}
            sortDir={filters.sortDir}
            onChange={onChange}
          /&gt;

          &lt;hr className="border-stone-100" /&gt;

          &lt;NarrowResultsSection
            filters={filters}
            onChange={onChange}
            countries={countries}
            colors={colors}
            modes={modes}
          /&gt;
        &lt;/div&gt;

        {/* Footer */}
        {activeFilterCount &gt; 0 &amp;&amp; (
          &lt;div className="px-5 py-4 border-t border-stone-100"&gt;
            &lt;button
              onClick={resetFilters}
              className="w-full flex items-center justify-center gap-2 px-4 py-2.5 
                         border border-stone-300 rounded-lg text-sm font-medium 
                         hover:bg-stone-100 transition text-stone-700"
            &gt;
              &lt;RotateCcw className="w-4 h-4" /&gt;
              Clear all filters
            &lt;/button&gt;
          &lt;/div&gt;
        )}
      &lt;/aside&gt;
    &lt;/&gt;
  );
};

export default Filter;
</code></pre>
<p>You can take this even further. Notice that <code>NarrowResultsSection</code> is the only component that uses the fetched <code>countries</code>, <code>colors</code>, and <code>modes</code>. And inside it, each <code>SelectField</code> uses a piece of this data.</p>
<pre><code class="language-typescript">import { FilterState } from "../../interfaces";
import { PriceRangeField } from "./price-range";
import { SelectField } from "./select-field";

interface NarrowResultsSectionProps {
  filters: FilterState;
  onChange: (partial: Partial&lt;FilterState&gt;) =&gt; void;
  countries: string[];
  colors: string[];
  modes: string[];
}

export function NarrowResultsSection({
  filters,
  onChange,
  countries,
  colors,
  modes,
}: NarrowResultsSectionProps) {
  return (
    &lt;section className="flex flex-col gap-4"&gt;
      &lt;h3 className="text-xs font-semibold uppercase tracking-wider text-stone-500"&gt;
        Narrow Results
      &lt;/h3&gt;

      &lt;SelectField
        label="Country"
        value={filters.country}
        options={countries}
        onChange={(v) =&gt; onChange({ country: v })}
        placeholder="All countries"
      /&gt;

      &lt;SelectField
        label="Color"
        value={filters.color}
        options={colors}
        onChange={(v) =&gt; onChange({ color: v })}
        placeholder="All colors"
      /&gt;

      &lt;SelectField
        label="Mode"
        value={filters.mode}
        options={modes}
        onChange={(v) =&gt; onChange({ mode: v })}
        placeholder="All modes"
      /&gt;

      &lt;PriceRangeField
        minPrice={filters.minPrice}
        maxPrice={filters.maxPrice}
        onChange={onChange}
      /&gt;
    &lt;/section&gt;
  );
}
</code></pre>
<p>Instead of fetching everything at the top and passing it down, you can give each <code>SelectField</code> its own query.</p>
<p>The <code>SelectField</code> looked like this:</p>
<pre><code class="language-typescript">interface SelectFieldProps {
  label: string;
  value: string;
  options: string[];
  onChange: (v: string) =&gt; void;
  placeholder: string;
}

export function SelectField({
  label,
  value,
  options,
  onChange,
  placeholder,
}: SelectFieldProps) {
  return &lt;&gt;{/*=== Renders UI ===*/}&lt;/&gt;;
}
</code></pre>
<p>Now, it looks like this:</p>
<pre><code class="language-typescript">import { useQuery } from "@tanstack/react-query";

interface SelectFieldProps {
  label: string;
  value: string;
  onChange: (v: string) =&gt; void;
  placeholder: string;
  queryFn(): Promise&lt;string[]&gt;;
  queryKey: string;
}

export function SelectField({
  label,
  value,
  onChange,
  placeholder,
  queryFn,
  queryKey,
}: SelectFieldProps) {
  const { data: options = [] } = useQuery({
    queryKey: [queryKey],
    queryFn: queryFn,
    staleTime: Infinity,
  });

  return &lt;&gt;{/*=== Renders UI ===*/}&lt;/&gt;;
}
</code></pre>
<p>Now each dropdown manages its own data. A state change inside one <code>SelectField</code> doesn't affect its siblings or its parent.</p>
<h4 id="heading-move-search-logic-into-its-component">Move Search Logic Into Its Component</h4>
<p>The <code>Search</code> component is the only component using the debouncing logic (<code>searchTimerRef</code>, <code>handleQueryChange</code>, <code>handleClearQuery</code>). You'll move logic inside the component:</p>
<pre><code class="language-typescript">"use client";

import { Search as SearchIcon, X } from "lucide-react";
import { ChangeEvent, useEffect, useRef } from "react";
import { FilterState } from "../interfaces";

interface SearchProps {
  query: string;
  onChange: (partial: Partial&lt;FilterState&gt;) =&gt; void;
}

const Search = ({ query, onChange }: SearchProps) =&gt; {
  const searchRef = useRef&lt;HTMLInputElement&gt;(null);
  const searchTimerRef = useRef&lt;ReturnType&lt;typeof setTimeout&gt; | null&gt;(null);

  const handleClearQuery = () =&gt; {
    if (searchRef.current) {
      searchRef.current.value = "";
    }

    onChange({ query: "" });
  };

  const handleQueryChange = (e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {
    const val = e.target.value;

    if (searchTimerRef.current) clearTimeout(searchTimerRef.current);

    searchTimerRef.current = setTimeout(() =&gt; {
      onChange({ query: val });
    }, 400);
  };

  useEffect(() =&gt; {
    return () =&gt; {
      if (searchTimerRef.current) clearTimeout(searchTimerRef.current);
    };
  }, []);

  return &lt;div&gt;{/*=== Renders UI ===*/}&lt;/div&gt;;
};

export default Search;
</code></pre>
<h4 id="heading-move-filter-chips-into-its-component">Move Filter Chips into Its Component</h4>
<p>The <code>FilterChips</code> component renders chips for active filters. The <code>hasPriceFilter</code> and <code>priceLabel</code> values that feed it can live inside the component instead of <code>SearchPage</code>:</p>
<pre><code class="language-typescript">interface FilterChipsProps {
  filters: FilterState;
  setFilters: (partial: Partial&lt;FilterState&gt;) =&gt; void;
  resetFilters: () =&gt; void;
}

export function FilterChips({
  filters,
  setFilters,
  resetFilters,
}: FilterChipsProps) {
  const priceLabel = [
    filters.minPrice ? `$${filters.minPrice}` : null,
    filters.maxPrice ? `$${filters.maxPrice}` : null,
  ]
    .filter(Boolean)
    .join(" - ");

  const hasPriceFilter = filters.minPrice || filters.maxPrice;

  return &lt;&gt;{/*=== Renders UI ===*/}&lt;/&gt;;
}
</code></pre>
<h4 id="heading-the-final-searchpage">The Final SearchPage</h4>
<p>After moving all state and logic to the components that need it, the <code>SearchPage</code> component looks like this:</p>
<pre><code class="language-typescript">"use client";

import { Header } from "./_components/header";
import { ProductTable } from "./_components/products-table";
import { FilterChips } from "./_components/filter-chips";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { FilterState, SortDir, SortField } from "./interfaces";

const DEFAULTS: FilterState = {
  query: "",
  country: "",
  color: "",
  mode: "",
  minPrice: "",
  maxPrice: "",
  sortField: "name",
  sortDir: "asc",
};

export default function SearchPage() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const filters: FilterState = {
    query: searchParams.get("q") ?? DEFAULTS.query,
    country: searchParams.get("country") ?? DEFAULTS.country,
    color: searchParams.get("color") ?? DEFAULTS.color,
    mode: searchParams.get("mode") ?? DEFAULTS.mode,
    minPrice: searchParams.get("minPrice") ?? DEFAULTS.minPrice,
    maxPrice: searchParams.get("maxPrice") ?? DEFAULTS.maxPrice,
    sortField:
      (searchParams.get("sortField") as SortField) ?? DEFAULTS.sortField,
    sortDir: (searchParams.get("sortDir") as SortDir) ?? DEFAULTS.sortDir,
  };

  const setFilters = (partial: Partial&lt;FilterState&gt;) =&gt; {
    const next = new URLSearchParams(searchParams.toString());
    const merged = { ...filters, ...partial };

    const keyMap: Record&lt;keyof FilterState, string&gt; = {
      query: "q",
      country: "country",
      color: "color",
      mode: "mode",
      minPrice: "minPrice",
      maxPrice: "maxPrice",
      sortField: "sortField",
      sortDir: "sortDir",
    };

    (Object.keys(merged) as (keyof FilterState)[]).forEach((k) =&gt; {
      const paramKey = keyMap[k];
      const val = merged[k];
      const def = DEFAULTS[k];
      if (val &amp;&amp; val !== def) {
        next.set(paramKey, val);
      } else {
        next.delete(paramKey);
      }
    });

    router.push(`\({pathname}?\){next.toString()}`, { scroll: false });
  };

  const resetFilters = () =&gt; {
    router.push(pathname, { scroll: false });
  };

  const activeFilterCount = [
    filters.country,
    filters.color,
    filters.mode,
    filters.minPrice,
    filters.maxPrice,
  ].filter(Boolean).length;

  return (
    &lt;div className="min-h-screen bg-stone-50"&gt;
      &lt;Header filters={filters} onChange={setFilters} /&gt;

      &lt;main className="max-w-6xl mx-auto px-4 py-6"&gt;
        {activeFilterCount &gt; 0 &amp;&amp; (
          &lt;FilterChips
            filters={filters}
            setFilters={setFilters}
            resetFilters={resetFilters}
          /&gt;
        )}

        &lt;ProductTable filters={filters} /&gt;
      &lt;/main&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Notice that <code>setFilters</code>, <code>resetFilters</code> and <code>activeFilterCount</code> are still in the <code>SearchPage</code> component. This is intentional. These values depend on the URL. Any component that reads from the URL will re-render whenever the URL changes. It doesn’t matter where the values are calculated.</p>
<h3 id="heading-fix-your-code-before-reaching-for-these-hooks">Fix Your Code Before Reaching For These Hooks</h3>
<p>You might be tempted to reach for <code>useCallback</code> or <code>useMemo</code> when you have infinite re-rendering. Unstable object reference often leads to infinite re-renders, especially when a child component has a <code>useEffect</code> that depends on the object. It’s always better to understand why the loop is happening and fix the root cause.</p>
<p>Look at this example:</p>
<pre><code class="language-typescript">"use client";

import { useEffect, useState } from "react";
import { fetchUsers, Filter, User } from "./utils";

interface UserListProps {
  filters: Filter;
  onLoad(data: User[]): void;
  users: User[];
}

function UserList({ filters, onLoad, users }: UserListProps) {
  console.count("__ USER LIST __");

  useEffect(() =&gt; {
    fetchUsers(filters).then((data) =&gt; {
      onLoad(data);
    });
  }, [filters, onLoad]);

  return (
    &lt;ul className="h-screen flex items-center justify-center flex-col"&gt;
      {users.map((u) =&gt; (
        &lt;li key={u.id}&gt;{u.name}&lt;/li&gt;
      ))}
    &lt;/ul&gt;
  );
}

const UserPage = () =&gt; {
  const [userData, setUserData] = useState&lt;User[]&gt;([]);

  const filters = {
    role: "admin",
    active: true,
  };

  return &lt;UserList filters={filters} onLoad={setUserData} users={userData} /&gt;;
};

export default UserPage;
</code></pre>
<p>The <code>UserList</code> component fetches users when it mounts. It uses <code>filters</code> and <code>onLoad</code> as dependencies.</p>
<p>The problem here is that the <code>filters</code> object in the <code>UserPage</code> component is recreated on every render. Even though the value looks the same, it’s a new reference each time there is a re-render. <code>UserList</code> sees it as a new value every time. This triggers its <code>useEffect</code> because it’s a dependency.</p>
<img src="https://cdn.hashnode.com/uploads/covers/629122ced97f80b5091d8058/c201dff7-3e6b-4648-8caf-9323057df3df.gif" alt="The browser showing infinite log of &quot;USER LIST&quot;." style="display:block;margin:0 auto" width="800" height="477" loading="lazy">

<p>Wrapping <code>filters</code> in <code>useMemo</code> will stop the loop, but it misses the real issue. <code>useMemo</code> isn't meant to stop infinite re-rendering. There are some better solutions to fix this:</p>
<p>The first option is to use primitives in the dependency array instead of objects. Object compares by reference. This is why the <code>useEffect</code> sees different references whenever it reads the <code>filter</code> props. Primitives compare by value.</p>
<pre><code class="language-typescript">function UserList({ filters, onLoad, users }: UserListProps) {
  console.count("__ USER LIST __");

  useEffect(() =&gt; {
    fetchUsers(filters).then((data) =&gt; {
      onLoad(data);
    });
  }, [filters.active, filters.role]); // primitives compare by value, not reference

  return (
    &lt;ul&gt;
      {users.map((u) =&gt; (
        &lt;li key={u.id}&gt;{u.name}&lt;/li&gt;
      ))}
    &lt;/ul&gt;
  );
}
</code></pre>
<p>The second option is to define the object outside the component so it has a stable reference.</p>
<pre><code class="language-typescript">const filters = {
  role: "admin",
  active: true,
};

const UserPage = () =&gt; {
  const [userData, setUserData] = useState&lt;User[]&gt;([]);

  return &lt;UserList filters={filters} onLoad={setUserData} users={userData} /&gt;;
};
</code></pre>
<p>The third solution is to store the object in a state if it's dynamic.</p>
<pre><code class="language-typescript">const UserPage = () =&gt; {
  const [userData, setUserData] = useState&lt;User[]&gt;([]);
  const [filters, setFilters] = useState({
    role: "admin",
    active: true,
  });

  return &lt;UserList filters={filters} onLoad={setUserData} users={userData} /&gt;;
};
</code></pre>
<h2 id="heading-when-to-use-usecallback-and-usememo">When to Use <code>useCallback</code> and <code>useMemo</code></h2>
<p>The goal of this article is not to tell you never to use these hooks. There are real situations where these hooks shine.</p>
<h3 id="heading-measure-before-you-optimize">Measure Before You Optimize</h3>
<p>Before going for any optimization, be it <code>useCallback</code>, <code>useMemo,</code> or restructuring your component, you should first confirm that there is a performance problem. Optimizing code that doesn’t need it isn’t beneficial to anybody.</p>
<p>React DevTools has a Profiler tab that lets you record a session and see exactly which components are re-rendering, how often, and how long each render takes. You should read <a href="https://www.freecodecamp.org/news/how-to-use-react-devtools/">How to Use React Developer Tools – Explained With Examples</a>. If you are a video person, you can watch how Ben shows <a href="https://www.youtube.com/watch?v=00RoZflFE34">how to use the React Profiler to find and fix performance problems</a>.</p>
<h3 id="heading-stabilize-references-for-reactmemo-children">Stabilize References for <code>React.memo</code> Children</h3>
<p><code>React.memo</code> prevents a component from re-rendering if its props haven't changed. But if you pass a function or object as a prop, the child will still re-render on every parent render because functions and objects are recreated with new references each time.</p>
<p>This is the right time to use <code>useCallback</code> or <code>useMemo</code>:</p>
<pre><code class="language-typescript">const Child = React.memo(({ onClick }: { onClick: () =&gt; void }) =&gt; {
  console.log("Child rendered");
  return &lt;button onClick={onClick}&gt;Click me&lt;/button&gt;;
});

function Parent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() =&gt; {
    console.log("clicked");
  }, []);

  return (
    &lt;&gt;
      &lt;button onClick={() =&gt; setCount((c) =&gt; c + 1)}&gt;Increment: {count}&lt;/button&gt;
      &lt;Child onClick={handleClick} /&gt;
    &lt;/&gt;
  );
}
</code></pre>
<p>Without <code>useCallback</code>, <code>Child</code> re-renders every time <code>count</code> changes, even though <code>handleClick</code> has nothing to do with <code>count</code>. With <code>useCallback</code>, the function reference stays stable.</p>
<p>It's often best to use both <code>useCallback</code> and <code>React.memo</code> together. But <code>React.memo</code> can be useful by itself if props are primitives or otherwise stable. And <code>useCallback</code> can be useful outside <code>React.memo</code>, such as when passing stable callbacks into effects, custom hooks, or third-party components.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p><code>useCallback</code> and <code>useMemo</code> are useful memoization tools, but they're not a free performance upgrade. Every call adds memory overhead and a dependency comparison on each render.</p>
<p>Always structure your components so that optimization is rarely needed. Move state and logic as close as possible to the components that use them. Use <code>useCallback</code> and <code>useMemo</code> along with <code>React.memo</code> after you confirm that renders are actually a problem.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
