What is ISR and what is it used for?
sobes.tech AI
Answer from AI
ISR (Incremental Static Regeneration) is a page caching mechanism in web applications that allows updating static pages after their initial build without resorting to a full rebuild of the entire site.
It is used for:
- Performance enhancement: Pages are served from cache, significantly speeding up load times for users.
- Data freshness: Allows updating content on static pages without manual or lengthy deployment processes.
- Reducing server load: Data is generated only when an update is needed, not on every request.
- SEO improvement: Search engines receive static pages, which helps better indexing.
It works by specifying a time after which the page should be regenerated in the background upon the next request after this time has elapsed. The user receives the old (cached) version of the page while regeneration occurs.
Example of usage in Next.js (one of the frameworks implementing ISR):
// pages/products/[id].js
export async function getStaticPaths() {
// Fetch paths for static page generation
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } },
],
fallback: true // allows generating pages on demand if they are not in paths
}
}
export async function getStaticProps({ params }) {
// Fetch data for the page
const res = await fetch(`https://api.example.com/products/${params.id}`);
const product = await res.json();
return {
props: {
product,
},
revalidate: 60 // Indicates that the page will be regenerated every 60 seconds
};
}
function Product({ product }) {
// Render the page
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
</div>
);
}
export default Product;
In this example, the product page will be statically generated during build time. After deployment, if a user visits the page more than 60 seconds after the previous request, the server will serve the cached version and trigger a background regeneration of the page with new data. The next user will then receive the updated version.