Published on Dec 5, 2023 08:14
Next JS: Page pre-rendering and Data fetching
Next.js provides several ways to pre-render pages and fetch data. The main concepts include:
- Page Pre-rendering:
- Static Generation (SG): Pages are generated at build time. This is the default method for most Next.js pages. The content is fixed at build time.
- Example: getStaticProps in Next.js allows you to fetch data and pre-render a page at build time.
- Static Generation (SG): Pages are generated at build time. This is the default method for most Next.js pages. The content is fixed at build time.
export async function getStaticProps() {
// Fetch data from an API
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Pass data to the page via props
return {
props: { data },
};
}
- Incremental Static Regeneration (ISR): Pages are initially generated at build time, but can be regenerated on-demand. This allows for updating content without rebuilding the entire site.
- Example: revalidate option in getStaticProps allows you to specify how often a page should be re-generated.
export async function getStaticProps() {
// Fetch data from an API
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Re-generate the page every 10 seconds
return {
props: { data },
revalidate: 10,
};
}
- Server-side Rendering (SSR): Pages are generated on each request. This is useful for pages that need to fetch data at runtime.
- Example: getServerSideProps allows you to fetch data on every request.
export async function getServerSideProps() {
// Fetch data from an API
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Pass data to the page via props
return {
props: { data },
};
}
2. Data Fetching:
- Client-Side Rendering (CSR): Data is fetched on the client side, typically using useEffect or other client-side data fetching methods.
- Example: Fetching data on the client side using React hooks.
import { useState, useEffect } from 'react';
const MyComponent = () => {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
const res = await fetch('https://api.example.com/data');
const result = await res.json();
setData(result);
};
fetchData();
}, []);
return (
<div>
<p>{data.message}</p>
</div>
);
};
- Server-Side Data Fetching: Data is fetched on the server side, either during static generation or server-side rendering.
- Example: Using getStaticProps or getServerSideProps to fetch data on the server side.
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data },
};
}
These concepts allow you to choose the most appropriate method for pre-rendering and data fetching based on the requirements of your Next.js application.