Files
b1089d3691 Update unstable_cache docs for revalidate option (#62689)
Clarifies what passing false or undefined to the revalidate property
option of unstable_cache does.

Context: I didn't want my DB query to be cached at all, but I did use
this API because I wanted to refresh a component's data after submitting
a server action. I thought I had to pass 0, or false to get it to not
cache at all.

Co-authored-by: Sam Ko <[email protected]>
2024-02-29 19:49:15 +00:00

49 lines
2.1 KiB
Plaintext

---
title: unstable_cache
description: API Reference for the unstable_cache function.
---
`unstable_cache` allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.
```jsx
import { getUser } from './data';
import { unstable_cache } from 'next/cache';
const getCachedUser = unstable_cache(
async (id) => getUser(id),
['my-app-user']
);
export default async function Component({ userID }) {
const user = await getCachedUser(userID);
...
}
```
> **Good to know**:
> Accessing dynamic data sources such as `headers` or `cookies` inside a cache scope is not supported. If you need this data inside a cached function use `headers` outside of the cached function and pass the required dynamic data in as an argument.
> **Warning**: This API is unstable and may change in the future. We will provide migration documentation and codemods, if needed, as this API stabilizes.
## Parameters
```jsx
const data = unstable_cache(fetchData, keyParts, options)()
```
- `fetchData`: This is an asynchronous function that fetches the data you want to cache. It must be a function that returns a `Promise`.
- `keyParts`: This is an array that identifies the cached key. It must contain globally unique values that together identify the key of the data being cached. The cache key also includes the arguments passed to the function.
- `options`: This is an object that controls how the cache behaves. It can contain the following properties:
- `tags`: An array of tags that can be used to control cache invalidation.
- `revalidate`: The number of seconds after which the cache should be revalidated. Omit or pass `false` to cache indefinitely or until matching `revalidateTag()` or `revalidatePath()` methods are called.
## Returns
`unstable_cache` returns a function that when invoked, returns a Promise that resolves to the cached data. If the data is not in the cache, the provided function will be invoked, and its result will be cached and returned.
## Version History
| Version | Changes |
| --------- | ---------------------------- |
| `v14.0.0` | `unstable_cache` introduced. |