While getStaticProps, getServerSideProps, and client-side fetching cover the majority of data fetching needs, Next.js offers more advanced techniques and patterns for optimizing performance and handling complex data scenarios. These include Incremental Static Regeneration (ISR), Automatic Static Optimization, and the use of data fetching libraries.
Incremental Static Regeneration (ISR)
ISR allows you to update static pages after the initial build without needing to rebuild the entire site. This is incredibly powerful for content that changes frequently but doesn't require real-time updates. You can revalidate static pages at specified intervals using the revalidate option in getStaticProps.
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data,
},
// Revalidate every 60 seconds
revalidate: 60,
};
}When a user requests a page with ISR enabled, Next.js will serve the stale static page immediately. In the background, it will re-fetch the data and regenerate the HTML. The next request will then receive the updated page. This provides a balance between the speed of static generation and the freshness of dynamic data.
graph LR
A[User Request] --> B{Is Page Stale?}
B -- Yes --> C[Serve Stale Page]
C --> D[Background Data Fetch & Rebuild]
D --> E[Update Static Page]
B -- No --> F[Serve Fresh Page]
E --> F
Automatic Static Optimization
Next.js automatically optimizes pages that don't use dynamic functions like getServerSideProps or getStaticProps with dynamic fallback values. These pages are pre-rendered to HTML at build time, resulting in excellent performance. If your page doesn't require runtime data fetching, Next.js handles the optimization for you.
Data Fetching Libraries
For more complex data fetching scenarios, especially involving caching, data synchronization, and mutation, consider using dedicated data fetching libraries. Popular choices in the React ecosystem that integrate well with Next.js include:
- SWR (Stale-while-revalidate): Developed by Vercel, SWR is a fantastic library for client-side data fetching. It provides hooks for fetching, caching, and revalidating data, along with features like request deduplication, interval polling, and focus revalidation. It significantly simplifies client-side data management.
- React Query (TanStack Query): Another powerful library that offers robust caching, background updates, and automatic retries for your server state. It's highly configurable and can manage complex data fetching logic with ease.