website-logomedcode

Next.js 15 : Caching Data server Side (use cache)

Next.js 15 is here, and it’s packed with features designed to take your web development experience to the next level. Among its standout
MED DAKIR| January 26, 2025
next.js
Next.js 15 : Caching Data server Side (use cache)

#Next.js #Cache #dev #blog

Next.js 15 Use Cache

What’s New in Next.js 15?

Next.js 15 is here, and it brings exciting updates that make it even easier for developers to create fast and efficient applications. One of the standout features of this version is its improved caching mechanisms, which can significantly enhance performance. With Next.js 15, you'll notice faster content loading times and a smoother user experience, even under high traffic conditions.


What’s particularly refreshing about this update is the way it simplifies caching strategies. Instead of needing to understand complex configurations, Next.js 15 enables developers to use caching with ease right out of the box. Plus, the new features are designed to integrate seamlessly into existing projects, so you don’t need to worry about a steep learning curve.

What is Caching in Next.js?

Caching is a method that stores frequently accessed data in a temporary storage location, allowing for quicker access on subsequent requests. Think of it like keeping a few snacks in your drawer; instead of going to the kitchen every time you're hungry, you can grab something tasty quickly.


In the context of Next.js, caching helps speed up page loads, improves performance, and reduces the load on servers. By storing static assets like images, scripts, and even HTML files temporarily, Next.js can serve these resources faster to users, making your web application feel snappier and more responsive.

How to Enable and Use Cache in Next.js 15

Enabling and using caching in Next.js 15 is straightforward! Here’s a simple guide to get you started:

  1. Enable support for the use cache directive with the useCache flag in your next.config.ts file:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
experimental: {
useCache: true,
},
}

export default nextConfig

You can then apply the use cache directive at the level of the file, component, or function.

// File level
'use cache'

export default async function Page() {
// ...
}
// Component level
export async function MyComponent() {
'use cache'
return <>
}
// Function level
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}

use cache is an experimental feature in Next.js, distinguishing it from built-in React features like use client or use server. Any arguments or props that can be serialized and are passed to the cached function, along with any serializable values drawn from the parent scope, will be formatted akin to JSON and will automatically become part of the cache key. In contrast, any non-serializable arguments, props, or values that are closed over will turn into opaque references within the cached function, allowing them to be passed along without inspection or modification. These non-serializable elements will be populated at the time of the request and will not be included in the cache key.

Examples

Caching complete routes with use cacheTo prerender a complete route, include use cache at the beginning of both the layout and page files. Each of these components is regarded as distinct entry points within your application and will be cached separately.

'use cache'
import { unstable_cacheLife as cacheLife } from 'next/cache'
export default function Layout({ children }: { children: ReactNode }) {
return(
{children}
    )}
Any components that are imported and nested within a page file will adopt the caching behavior of that page.

'use cache'

import { unstable_cacheLife as cacheLife } from 'next/cache'

 

async function Users() {

  const users = await fetch('/api/users')

  // loop through users

}

 

export default function Page() {

  return (

    <main>

      <Users />

    </main>

  )

}

Caching component output with use cache


You can utilize useCache at the component level to store any data fetching or calculations carried out within that component. When the component is reused across your application, it can access the same cache entry, provided that its props keep the same structure.


The props are serialized and contribute to the cache key, allowing the cache entry to be reused as long as the serialized props yield the same value in each occurrence.







Login to write a comment

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policyTerms & Conditions