Skip to content

useDeepMemo

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

useDeepMemo

Like React's native useMemo, but it compares dependencies using deep structural equality instead of strict reference equality (===). This is incredibly useful when you're forced to consume dependencies that are technically recreated on every render but contain the exact same data.

Usage Examples

Basic

Preventing an expensive calculation from running when an object dependency is recreated but unchanged.

import { useDeepMemo } from "react-hook-lab";

function DataProcessor({ filters }: { filters: { status: string; sort: string } }) {
  // If the parent passes a new object literal like {{ status: 'active', sort: 'asc' }} 
  // on every render, standard useMemo would fail and recalculate every time.
  // useDeepMemo correctly identifies that the data inside is structurally identical!
  const processedData = useDeepMemo(() => {
    console.log("Expensive processing running...");
    return processHeavyData(filters);
  }, [filters]);

  return <div>{processedData.length} items found</div>;
}

Common

Memoizing API configurations or fetching logic where query parameters are often assembled as inline array/object literals.

import { useDeepMemo, useResource } from "react-hook-lab";

function UserList({ userIds }: { userIds: string[] }) {
  // userIds might be a brand new array reference on every render `['1', '2']`.
  // useDeepMemo prevents the search query from being endlessly regenerated.
  const queryConfig = useDeepMemo(() => ({
    url: "/api/users",
    method: "POST",
    body: JSON.stringify({ ids: userIds })
  }), [userIds]);

  const { data } = useResource("users", () => fetch(queryConfig.url, queryConfig).then(r => r.json()));

  return <div>Loaded Users</div>;
}

API Reference

Parameters

  • factory
    • Type: () => T
    • Description: The function that computes and returns the value you want to memoize.
  • deps
    • Type: DependencyList
    • Description: An array of dependencies that the factory function relies on.

Return Type

Returns T, the computed value returned by the factory function.

Core Working

Under the hood, useDeepMemo relies on a highly optimized, custom deepEqual function. It stores the previous dependencies in a useRef. On every render, instead of letting React do its standard shallow comparison, the hook runs deepEqual(prevDeps, newDeps). If the structural data inside the dependencies is identical (even if the memory references are completely different), it skips the factory function and returns the cached value.

Clone this wiki locally