In this tutorial, you will learn how to use static data fetching in Next.js
What is static Data Fetching?
Static Data Fetching means data is fetched at build time, and the page is generated as a static HTML page.
How does it work?
1. Data is fetched when the project is built.
2. HTML is pre-rendered.
It has some common methods
1. getStaticProps() (Pages Router)
2. fetch() with cache: ‘force-cache’ (App Router)
3. Static Server Components
Example:
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
cache: 'force-cache'
});
return res.json();
}
export default async function Page() {
const posts = await getPosts();
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
Advantages of static Data Fetching
There are many advantages of static Data Fetching.
1. It is good for SEO.
2. It is CDN-friendly.
3. It is good for performance.
4. It has lower server cost.
Disadvantages of Static Data Fetching
There are some disadvantages of Static Data Fetching.
1. Data can become outdated
2. Not suitable for user-specific data.
Static Data Fetching in Next.js – Interview Questions
Q 1: What is static data fetching?
Q 2: How is static data fetched in App Router?
Q 3: What are benefits of static data fetching?
Q 4: Is static data SEO-friendly?
Q 5: Can static data be revalidated?
Static Data Fetching in Next.js – Objective Questions (MCQs)
Q1. Static data fetching means data is fetched:
Q2. Which rendering method uses static data fetching?
Q3. Static data fetching is best suited for:
Q4. Which option enables page revalidation?
Q5. Static data fetching improves: