Performance: Why caching is central to Next.js
Caching in Next.js affects page load speed and reduces server response time by reusing previously generated content.
export async function getStaticProps() { const data = await fetch('https://api.example.com/data'); const json = await data.json(); return { props: { json }, revalidate: 60 }; } // Static generation with incremental static regeneration caches page for 60 seconds
export async function getServerSideProps() { const data = await fetch('https://api.example.com/data'); const json = await data.json(); return { props: { json } }; } // This runs on every request, no caching
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Server-side rendering on every request | N/A | N/A | High due to slow server response | [X] Bad |
| Static generation with caching | N/A | N/A | Low due to fast server response | [OK] Good |
revalidate property to set cache refresh timing.getStaticProps fetches data at build time, useEffect runs on client, getServerSideProps fetches on every request.revalidate: 10 in getStaticProps?revalidate: 10 means Next.js will refresh the cached page every 10 seconds.revalidate: '10' (string) instead of 10 (number). What happens?revalidate as a number, not a string.revalidate means data updates often but still uses cache for speed.getServerSideProps fetches every time but is slower; very high revalidate delays updates; disabling cache hurts speed.revalidate to a low number like 5 seconds. -> Option CPass the test and this pattern moves unknown