0
0
NextJSframework~5 mins

Data cache behavior in NextJS

Choose your learning style9 modes available
Introduction

Data cache helps your app load faster by saving information so it doesn't have to fetch it again. It makes your app feel quick and smooth.

When you want to show data that doesn't change often, like a blog post or product details.
When users visit the same page multiple times and you want to avoid waiting for data to load again.
When you want to reduce the number of requests to your server or external APIs.
When you want to improve app performance on slow internet connections.
When you want to keep data available even if the user goes offline briefly.
Syntax
NextJS
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json())
  return {
    props: { data },
    revalidate: 10 // seconds
  }
}

getStaticProps runs at build time and caches the data for fast loading.

The revalidate option tells Next.js to update the cache after the given seconds.

Examples
This caches blog posts and refreshes the cache every 60 seconds.
NextJS
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/posts').then(res => res.json())
  return { props: { posts: data }, revalidate: 60 }
}
This fetches fresh data on every request without caching.
NextJS
export async function getServerSideProps() {
  const data = await fetch('https://api.example.com/user').then(res => res.json())
  return { props: { user: data } }
}
This uses client-side caching with SWR to keep data fresh and fast.
NextJS
import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)
  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>
  return <div>Hello {data.name}</div>
}
Sample Program

This React component uses Next.js with the SWR library to cache user data on the client side. It shows loading text while fetching, an error message if fetching fails, and the user info when ready.

NextJS
import useSWR from 'swr'

const fetcher = url => fetch(url).then(res => res.json())

export default function UserProfile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <p>Failed to load user data.</p>
  if (!data) return <p>Loading user data...</p>

  return <main>
    <h1>User Profile</h1>
    <p>Name: {data.name}</p>
    <p>Email: {data.email}</p>
  </main>
}
OutputSuccess
Important Notes

Next.js supports different caching methods: static generation, server-side rendering, and client-side caching.

Use revalidate in getStaticProps to keep static pages updated.

Client-side caching with SWR or React Query helps keep data fresh without full page reloads.

Summary

Data caching makes your app faster by saving and reusing data.

Next.js offers caching at build time, on each request, and on the client side.

Choose caching based on how often your data changes and how fresh it needs to be.