React 19's cache() Function

React 19's cache() Function

Introduction

The cache() function in React 19 is designed to improve performance in React Server Components by preventing unnecessary duplicate work.

What It Does

  1. Remembers Results: It wraps around a function and remembers what that function returned for specific inputs.

  2. Shares Data: When multiple components need the same data, they get the cached result instead of fetching it again.

How to Use It

import { cache } from "react";

// Create a memoized function outside components
const getUser = cache(async (userId) => {
  return await db.getUser(userId);
});

// Use it in multiple components
function ProfileHeader({ userId }) {
  const user = getUser(userId);
  // ...
}

function ProfileStats({ userId }) {
  const user = getUser(userId);
  // ...
}

Important Rules

  1. Server-Only: Only works in React Server Components, not client components.

  2. Define Outside Components: Create memoized functions outside components and import them where needed.

  3. Same References Matter: If you pass objects or arrays as arguments, they need to be the same reference to hit the cache.

  4. Fresh Per Request: The cache resets with each new server request.

  5. Preload Pattern: You can start fetching data early without awaiting, then await later when you need it:

     function Page({ userId }) {
       // Start fetching but don't wait
       getUser(userId);
    
       return (
         <>
           <OtherContent />
           <Profile userId={userId} /> {/* Will use the already-started fetch */}
         </>
       );
     }
    

Common Mistakes to Avoid

  1. Creating the memoized function inside a component (creates a new cache each render)

  2. Using different memoized functions for the same data (they don't share caches)

  3. Calling memoized functions outside of components (won't use the cache)

    1. Memoized functions from cache() must be called inside React components to actually access the cache. If you call them outside of a component context, they'll still run the original function but won't look for cached results or store new results in the cache.
  4. Using complex objects as keys without ensuring same reference

Main Benefits

  1. Stops Repeating Work: Components can share results, so they don't all do the same task.

  2. Prevents Fetch Delays: Start getting data early in the component tree.

  3. Keeps Components Independent: Components can get their own data without repeating tasks.