Let's talk about Next.js data fetching in 2024. Getting data is super important for any website, and Next.js has cool ways to do it. We'll check out the main ways and see some examples in code!
The Usual Suspects: SSG, ISR, and SSR
We've all heard of these three: Static Site Generation (SSG), Incremental Static Regeneration (ISR), and Server-Side Rendering (SSR). They're still the main players, but how we use them has evolved.
- SSG: Best for content that rarely changes, like blog posts. Think of it like pre-baking a cake – the content is ready to go when someone visits the page, giving you great SEO and super-fast loading times.
JavaScript
// getStaticProps at build time fetches data
export async function getStaticProps() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return {
props: { posts },
};
}
function MyBlogPost({ posts }) {
return (
<div>
<h1>My Awesome Blog</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
ISR: The in-between option. Pages are pre-rendered but can be refreshed in the background or when requested. This is great for content that updates sometimes, like news articles. Like keeping your cake fresh
JavaScript // getStaticProps at build time and revalidated periodically export async function getStaticProps() { const res = await fetch('https://api.example.com/news'); const news = await res.json(); return { props: { news }, revalidate: 60, // Revalidate every minute }; } function NewsPage({ news }) { return ( <div> <h1>Latest News</h1> <ul> {news.map((article) => ( <li key={article.id}>{article.headline}</li> ))} </ul> </div> ); }
SSR: Perfect for super dynamic content or personalized experiences. The data is grabbed every single time someone visits the page. Think of it like making a custom cake for each visitor – it's flexible but might take a bit longer.
JavaScript // getServerSideProps on every request export async function getServerSideProps(context) { const userId = context.req.cookies.userId; const res = await fetch(`https://api.example.com/user/${userId}`); const user = await res.json(); return { props: { user }, }; } function ProfilePage({ user }) { return ( <div> <h1>Welcome, {user.name}!</h1> <p>Your profile details...</p> </div> ); }
Choosing Your Weapon: It Depends!
SEO focus with low updates? SSG is your friend.
Need some updates but want speed? ISR is the way to go.
Super dynamic or personalized content? SSR is your best bet.
Bonus Tip: Keep it Fresh with Revalidation
For SSG and ISR, you can define how often Next.js revalidates the data to keep things fresh. This is especially important for ISR to ensure users get the latest updates.
Looking Ahead: More Tools in the Toolbox
Next.js is constantly evolving, and data fetching is no exception. Here are some cool things to keep an eye on:
Streaming: Great for handling massive datasets by fetching data in chunks, improving initial load times.
Data Fetching Libraries: Leverage libraries like SWR or React Query for advanced caching and data management across components.
The future of data fetching in Next.js is likely hybrid. We'll see developers combining strategies like SSG with selective SSR for specific components. This lets you optimize performance while maintaining dynamic elements.