DeployU
Interviews / Frontend Engineering / How do you do data fetching in Next.js?

How do you do data fetching in Next.js?

practical Data Fetching Interactive Quiz Code Examples

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?

Wrong Approach

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.

Right Approach

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

MethodDescription
getStaticPropsFetches data at build time.
getStaticPathsSpecifies which dynamic routes to pre-render at build time.
getServerSidePropsFetches data on each request.
getInitialPropsAn older data fetching method that runs on both the server and the client. It is not recommended for new projects.
Client-side fetchingFetches data on the client.

Step 2: Choose the Right Tool for the Job

Use CaseRecommended Method
A blog post or a product cataloggetStaticProps
A page with a large number of dynamic routesgetStaticPaths
A page with personalized datagetServerSideProps
A page with real-time dataClient-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?