Next.js - use cache Directive



The "use cache" Directive

The "use cache" is a Next.js directive used to force the caching of a component or a function in application. You can define the directive at the top of any file to indicate that all exports in the file are cacheable, or inline at the top of a function or component to inform Next.js that the return value should be cached and reused for subsequent requests.

Example

This a simple example of "use cache" directive at the top of a component:

"use cache"

// File starts from here
import react from 'react'

export default function Home() {
  return <div>Hello, Next.js!</div>
}
The use cache directive is an experimental feature available only in canary channels and a subject to change.

Enable Support For "use cache"

As mentioned above, the "use cache" directive is an experimental feature, so you need to enable it in your project. To do that, you need set dynamicIO flag as true in your 'next.config.js' file.

// File: next.config.js

import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  experimental: {
    dynamicIO: true,
  },
}
 
export default nextConfig

Caching Entire Routes

To prerender all the routes in your application, you can use the "use cache" directive at the top of layout component and page component. This is because the these components serves as the entry point for all the routes in your application.

'use cache'

import { unstable_cacheLife as cacheLife } from 'next/cache'
 
export default function Layout({ children }: { children: ReactNode }) {
  return <div>{children}</div>
}

Output

The image below shows caching for the page we made in the previous chapter. Caches for all routes are stored and retrieved at user's browser.

All Routes cache

Caching Function Output

You can use "use cache" directive inside a function to cache the return value of the function in Next.js. This is useful when you want to cache the network request, database query, or any other complex operation.

export async function getData() {
    'use cache'
    
    const data = await fetch('/api/data')
    return data
}

Output

The image below shows the output of the code above. You can see that the data is fetched from the server and cached in the browser.

Next.js Function Cache
Advertisements