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.
Data cache behavior in 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.
export async function getStaticProps() { const data = await fetch('https://api.example.com/posts').then(res => res.json()) return { props: { posts: data }, revalidate: 60 } }
export async function getServerSideProps() { const data = await fetch('https://api.example.com/user').then(res => res.json()) return { props: { user: data } } }
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> }
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.
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> }
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.
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.