# cache()

> The `cache()` API in React caches the result of a data fetch or computation for Server Components.

## How do I deduplicate data fetching with cache() in React?

The API for Server Components that wraps a function and caches its result for the same arguments during a single server request. Allows several components to request the same data without duplicate fetches.

- Topic: APIs
- Type: API

## Example

Wrong:

```jsx
async function Profile({ id }) {
  const getUser = cache((id) => db.user.find(id));
  const user = await getUser(id);
  return <h1>{user.name}</h1>;
}
```

Right:

```jsx
const getUser = cache((id) => db.user.find(id));
async function Profile({ id }) {
  const user = await getUser(id);
  return <h1>{user.name}</h1>;
}
```

A module-level cached function is shared by every component in the request, so the same user is fetched only once.

## Common mistakes

- Calling `cache()` inside a component, creating a new empty cache on each render.
- Expecting the cache to persist between requests, while it lives only for one server request.

## Key points

- `cache()` is called at module level, not inside a component, so all callers share one cached function.
- It is used only in Server Components, not in files marked `'use client'`.
- Arguments are primitives or stable references, since objects are compared by identity.

## Interview questions

### cache() vs useMemo: what is the difference?

`cache()` shares a result across components during one server request. `useMemo` stores a value inside one component between its renders.

### Does cache() work in Client Components?

No. It is meant for Server Components; in Client Components use `useMemo` or a data library that caches requests.

## Related cards

- [cacheSignal()](https://wonderium.dev/react/cache-signal.md)
- [Server Components](https://wonderium.dev/react/server-components.md)
- [useMemo()](https://wonderium.dev/react/use-memo.md)
- [memo()](https://wonderium.dev/react/memo.md)
- [use()](https://wonderium.dev/react/use.md)

---

- Level: [React](https://wonderium.dev/react.md)
- HTML version: https://wonderium.dev/react/cache
- Last updated: 2026-11-25
