Cache in Next.js 16

8 min readBy Saman Kefayatpour
Cache in Next.js 16

'use cache' in Next.js 16

use cache is a new feature in Next.js 16 that allows developers to cache the results of data fetching for pages, components, or functions. This can significantly improve application performance by reducing the number of network requests and speeding up page load times.

Cache in React vs 'use cache' in Next.js

Both cache and use cache are server-based, but cache in React is request-based caching, while use cache in Next.js is file, component- and function-level caching.

How 'use cache' Works

The use cache directive can be added to any server-side page, component or function. When it is called, Next.js checks if the result is already cached. If it is, the cached result is returned immediately. If not, the function executes, fetches the data, and stores the result in the cache for future use.

To activate use cache, you need to enable cacheComponents in your next.config.js file:

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

Here's an example of how to use use cache and cache in a Next.js component:

//react request based caching in Data fetching function import { cache } from 'react' export const getData = cache(async () => { return await db .select() .from(dataTable) });
//component and function based caching const DataComponent = async () => { 'use cache'; // Next.js function based caching cacheLife({ // Set cache duration stale: 3600, // 1 hour stale time on client revalidate: 86400, // 24 hours alive before revalidation on server }) cacheTag('data-component'); // Tag for cache invalidation const data = await getData(); if (!data) { return <DataSkeleton />; } return ( <div> {data.map((d) => ( <DataCard key={d.id} data={d} /> ))} </div> ); };
'use server' import { updateTag } from 'next/cache' export async function updateProduct() { await db.products.update(...) updateTag('products') // Invalidates all 'products' caches }

Explanation:

  • The getData function uses React's cache to store the results of a database query. This means that if getData is called multiple times during the same request, it will only execute the database query once.
  • The DataComponent function uses use cache to cache the entire component's output. This means that if DataComponent is rendered multiple times, it will return the cached output instead of re-executing the function.
  • The cacheLife function sets the caching duration for the component.

cacheLife:

  • stale: The duration (in seconds) for which the cached data is considered fresh on the client side. Default is 5 minutes.
  • revalidate: The duration (in seconds) for which the cached data remains valid on the server side before it needs to be revalidated. Default is 15 minutes.
  • expire: The total duration (in seconds) after which the cached data will be removed from the cache. Default is never.

cacheTag:

  • cacheTag allows you to assign tags to cached data. This is useful for cache invalidation, as you can invalidate all cached data associated with a specific tag when the underlying data changes.

updateTag:

  • updateTag is a server-side function (within Server Actions) that allows you to invalidate cached data associated with a specific tag. This is useful when you update data in your database and want to ensure that the cached data is refreshed.

revalidateTag:

  • revalidateTag is another server-side function that allows you to revalidate cached data associated with a specific tag in the background. This is useful for keeping cached data up-to-date without blocking the user experience.

Side Effects and Considerations

Next.js 16 has two types of components:

  1. client components which use use client directive
  2. server components
    • static one which use use cache directive
    • dynamic one which don't use use cache directive but must be load in Suspense boundary.

Can we call client components inside server components or vice versa?

  • Client components can be called inside server components.
  • Server components can be called inside client components by using the donut pattern..

Conclusion

The use cache feature in Next.js 16 provides a powerful way to enhance the performance of web applications by caching data fetching results at the component level. By leveraging this feature, developers can reduce network requests, speed up page load times, and create a more responsive user experience.