Next.js handles data fetching differently because it mixes server and client work to make websites faster and easier to build.
Why data fetching differs in Next.js
Start learning this pattern below
Jump into concepts and practice - no test required
export async function getServerSideProps(context) { // fetch data here const data = await fetchData(); return { props: { data } }; } export async function getStaticProps() { // fetch data here const data = await fetchData(); return { props: { data } }; } // Client-side fetching inside a React component import { useEffect, useState } from 'react'; function Component() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }
getServerSideProps runs on the server on every request.
getStaticProps runs at build time to create static pages.
export async function getServerSideProps(context) { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
export async function getStaticProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
import { useEffect, useState } from 'react'; function Page() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }
This example shows data fetched at build time for the post content, making the page fast to load. Comments are fetched on the client after the page loads, so users see the post immediately and comments appear shortly after.
import { useState, useEffect } from 'react'; export async function getStaticProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); return { props: { post } }; } export default function PostPage({ post }) { const [comments, setComments] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts/1/comments') .then(res => res.json()) .then(setComments); }, []); return ( <main> <h1>{post.title}</h1> <p>{post.body}</p> <section aria-label="Comments"> <h2>Comments</h2> {comments ? ( <ul> {comments.map(c => ( <li key={c.id}> <strong>{c.name}:</strong> {c.body} </li> ))} </ul> ) : ( <p>Loading comments...</p> )} </section> </main> ); }
Server-side fetching helps with SEO and fast first load.
Client-side fetching is good for data that changes often or depends on user actions.
Static generation is best for pages that don't change often.
Next.js uses different ways to fetch data depending on when and how you want it.
Server-side and static fetching happen before the page shows, client-side fetching happens after.
Choosing the right method helps your site load faster and work better for users.
Practice
Solution
Step 1: Understand data fetching timing in Next.js
Next.js allows fetching data before the page loads (server-side or static) or after the page loads (client-side).Step 2: Recognize the reason for multiple methods
Using different methods helps improve performance and user experience by choosing the best time to fetch data.Final Answer:
Because data can be fetched at different times for better performance -> Option DQuick Check:
Data fetching timing = A [OK]
- Assuming Next.js only fetches data on the server
- Believing client-side fetching is not supported
- Thinking all data must be static
Solution
Step 1: Identify build-time data fetching method
Next.js usesgetStaticPropsto fetch data at build time for static generation.Step 2: Compare options with Next.js conventions
getServerSidePropsis for server-side rendering, not build time; others are invalid function names.Final Answer:
export async function getStaticProps() { return { props: {} } } -> Option AQuick Check:
Build-time fetch = getStaticProps A [OK]
- Confusing getServerSideProps with getStaticProps
- Using incorrect function names
- Thinking client-side fetching uses special props functions
getServerSideProps to fetch data that changes every second?Solution
Step 1: Understand getServerSideProps behavior
This function runs on every request, so it fetches fresh data each time the page loads.Step 2: Apply to data changing every second
Since data changes frequently, getServerSideProps ensures the page always shows the latest data.Final Answer:
The page shows the latest data on every request -> Option CQuick Check:
Server-side fetch = fresh data B [OK]
- Thinking getServerSideProps caches data at build time
- Assuming data never updates after first load
- Believing it causes errors with fast-changing data
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data')
const data = await res.json()
return { data }
}Solution
Step 1: Check return value format in getStaticProps
Next.js expects an object with apropskey containing the data, not just data alone.Step 2: Identify the missing wrapper
The code returns{ data }but should return{ props: { data } }for Next.js to pass props correctly.Final Answer:
Missing return of props object wrapping data -> Option AQuick Check:
Return props object = C [OK]
- Returning data directly without props wrapper
- Thinking fetch is disallowed in getStaticProps
- Believing async functions are forbidden
Solution
Step 1: Analyze requirements for fast initial load and frequent updates
Static data can be fetched at build time for fast load; user-specific data changes often and should be fetched client-side.Step 2: Evaluate options
Use getStaticProps to fetch data and revalidate every second revalidates too frequently and may cause performance issues; Use getServerSideProps to fetch data on every request delays initial load; Fetch all data client-side only after page loads delays all data; Use getStaticProps for static data and fetch user data client-side after load balances fast load and fresh user data.Final Answer:
Use getStaticProps for static data and fetch user data client-side after load -> Option BQuick Check:
Static + client fetch = D [OK]
- Using only server-side fetching causing slow load
- Fetching everything client-side causing blank initial page
- Overusing revalidation causing unnecessary server load
