Fetching data is a key part of creating web applications, and Next.js offers several methods for doing so, each designed for different situations. Let's explore each technique:
Server-Side Rendering (SSR):
In SSR, data fetching occurs on the server before sending the HTML to the client.
This technique is ideal for scenarios where you need to fetch data that is specific to each request, such as personalized content or data that frequently changes.
Next.js facilitates SSR through the
getServerSideProps
function, which allows you to fetch data asynchronously and pass it as props to your components.
Example:
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }, // Pass data as props to the component
};
}
Static Site Generation (SSG):
SSG generates HTML pages at build time, allowing for fast and efficient delivery of content to users.
This technique is suitable for data that doesn't change frequently and can be pre-rendered ahead of time.
Next.js offers
getStaticProps
andgetStaticPaths
functions to enable SSG.getStaticProps
fetches data at build time, whilegetStaticPaths
allows dynamic routes to be pre-rendered.
Example:
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }, // Pass data as props to the component
};
}
Client-Side Data Fetching:
Client-side data fetching occurs after the initial HTML has been delivered to the client, typically in response to user interactions or dynamic updates.
This technique is suitable for fetching data that is not required for the initial render or needs to be updated frequently.
Next.js allows you to perform client-side data fetching using standard methods such as
fetch
, Axios, or GraphQL client libraries like Apollo Client.
Example:
import { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const res = await fetch('https://api.example.com/data');
const result = await res.json();
setData(result);
}
fetchData();
}, []);
return (
<div>
{data ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
}
By learning how to use the data fetching methods that Next.js offers, you can handle data well in your apps, improve performance, and make the user experience smooth.