Questions
How do you do data fetching in Next.js?
The Scenario
You are a frontend engineer at a social media company. You are building a new page that needs to fetch data from an API and then render it.
You are not sure which of the different data fetching methods in Next.js you should use.
The Challenge
Explain the different data fetching methods in Next.js. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might only be aware of `getInitialProps`. They might not be aware of the other data fetching methods or the trade-offs between them.
A senior engineer would be able to provide a detailed explanation of all the different data fetching methods in Next.js. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Different Data Fetching Methods
| Method | Description |
|---|---|
getStaticProps | Fetches data at build time. |
getStaticPaths | Specifies which dynamic routes to pre-render at build time. |
getServerSideProps | Fetches data on each request. |
getInitialProps | An older data fetching method that runs on both the server and the client. It is not recommended for new projects. |
| Client-side fetching | Fetches data on the client. |
Step 2: Choose the Right Tool for the Job
| Use Case | Recommended Method |
|---|---|
| A blog post or a product catalog | getStaticProps |
| A page with a large number of dynamic routes | getStaticPaths |
| A page with personalized data | getServerSideProps |
| A page with real-time data | Client-side fetching |
Step 3: Code Examples
Here are some code examples that show the difference between the different approaches:
getStaticProps:
export async function getStaticProps() {
const res = await fetch('https://.../data')
const data = await res.json()
return { props: { data } }
}getServerSideProps:
export async function getServerSideProps() {
const res = await fetch('https://.../data')
const data = await res.json()
return { props: { data } }
}Client-side fetching:
import { useState, useEffect } from 'react'
function MyComponent() {
const [data, setData] = useState(null)
useEffect(() => {
async function fetchData() {
const res = await fetch('https://.../data')
const data = await res.json()
setData(data)
}
fetchData()
}, [])
// ...
} Practice Question
You are building a page that displays a list of products. The list of products changes frequently. Which of the following would be the most appropriate?