react-code-dataset
/
next.js
/docs
/01-app
/03-api-reference
/05-config
/01-next-config-js
/cacheComponents.mdx
| --- | |
| title: cacheComponents | |
| description: Learn how to enable the cacheComponents flag in Next.js. | |
| version: canary | |
| --- | |
| The `cacheComponents` flag is an experimental feature in Next.js that causes data fetching operations in the App Router to be excluded from pre-renders unless they are explicitly cached. This can be useful for optimizing the performance of dynamic data fetching in Server Components. | |
| It is useful if your application requires fresh data fetching during runtime rather than serving from a pre-rendered cache. | |
| It is expected to be used in conjunction with [`use cache`](/docs/app/api-reference/directives/use-cache) so that your data fetching happens at runtime by default unless you define specific parts of your application to be cached with `use cache` at the page, function, or component level. | |
| ## Usage | |
| To enable the `cacheComponents` flag, set it to `true` in the `experimental` section of your `next.config.ts` file: | |
| ```ts filename="next.config.ts" | |
| import type { NextConfig } from 'next' | |
| const nextConfig: NextConfig = { | |
| experimental: { | |
| cacheComponents: true, | |
| }, | |
| } | |
| export default nextConfig | |
| ``` | |
| When `cacheComponents` is enabled, you can use the following cache functions and configurations: | |
| - The [`use cache` directive](/docs/app/api-reference/directives/use-cache) | |
| - The [`cacheLife` function](/docs/app/api-reference/config/next-config-js/cacheLife) with `use cache` | |
| - The [`cacheTag` function](/docs/app/api-reference/functions/cacheTag) | |
| ## Notes | |
| - While `cacheComponents` can optimize performance by ensuring fresh data fetching during runtime, it may also introduce additional latency compared to serving pre-rendered content. | |