What is Data Cache in Next.js: Explanation and Example
data cache refers to storing fetched data temporarily to speed up page loads and reduce repeated requests. It helps Next.js serve data faster by reusing previously fetched results instead of fetching them again.How It Works
Think of data cache in Next.js like a memory box where your app keeps copies of data it already fetched. When your app needs the same data again, it looks in this box first instead of asking the server again. This saves time and makes your app feel faster.
Next.js uses caching especially when fetching data for pages during server-side rendering or static generation. It stores the data temporarily so if a user visits the same page again, Next.js can quickly provide the cached data without waiting for a new fetch.
This process is similar to how your web browser caches images or files to avoid downloading them repeatedly. Data cache in Next.js improves performance and reduces load on your backend.
Example
This example shows how Next.js caches data when using getStaticProps to fetch data at build time. The data is cached and reused for every request until you rebuild the app or until the revalidation time expires.
export async function getStaticProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); return { props: { post }, revalidate: 10 // seconds to cache before regenerating }; } export default function Post({ post }) { return ( <main> <h1>{post.title}</h1> <p>{post.body}</p> </main> ); }
When to Use
Use data cache in Next.js when you want to improve page load speed and reduce server load by avoiding repeated data fetching. It is especially useful for pages that do not change often, like blog posts, product listings, or documentation.
For example, if you have a blog, caching the post data means visitors get instant page loads without waiting for the server to fetch the post every time. You can control cache duration with revalidate in getStaticProps or use built-in caching in API routes.
Key Points
- Data cache stores fetched data temporarily to speed up page loads.
- Next.js caches data during static generation and server-side rendering.
- Use
revalidateto control cache duration for static pages. - Caching reduces repeated requests and improves user experience.
- Ideal for data that changes infrequently.