Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views9 pages

Next - Js Data Fetching Patterns

Uploaded by

phonhub2nd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Next - Js Data Fetching Patterns

Uploaded by

phonhub2nd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

TheDevSpace | Full-Stack Web Development Course

Next.js Data Fetching Patterns


Cheat Sheet
By Eric H
Next.js offers multiple ways to fetch data for your pages and
components, supporting both static and dynamic use cases.

This guide covers the most common data fetching patterns in


Next.js.

Tip

Learn how to build your first SaaS with Next.js at


thedevspace.io

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

1. Fetching in Server Components


(Recommended)
Use fetch directly in async server components for static or
dynamic data.

Examples

1 // app/page.js
2 export default async function Page() {
3 // Static fetch (default)
4 const res = await
fetch("https://api.example.com/posts");
5 const posts = await res.json();
6
7 // Dynamic fetch (on every request)
8 const res2 = await
fetch("https://api.example.com/time", {
9 cache: "no-store",
10 });
11 const time = await res2.json();
12
13 return (
14 <div>
15 <h1>Posts</h1>
16 {posts.map((p) => (
17 <div key={p.id}>{p.title}</div>
18 ))}
19 <div>Server time: {time.now}</div>
20 </div>
21 );
22 }

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

2. Static Data Fetching (Default)


By default, fetches in server components are static and cached at
build time or on-demand.

Example

1 // app/page.js
2 export default async function Home() {
3 const res = await
fetch("https://api.example.com/data");
4 const data = await res.json();
5 return <div>{data.message}</div>;
6 }

3. Dynamic Data Fetching


Force dynamic fetch with { cache: "no-store" } or export
const dynamic = "force-dynamic" .

Example

1 export const dynamic = "force-dynamic";


2
3 export default async function Page() {
4 const res = await
fetch("https://api.example.com/time");
5 const data = await res.json();
6 return <div>Dynamic: {data.time}</div>;
7 }

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

4. Fetching in Client Components


Use React hooks like useEffect and useState for client-side
data fetching.

Example

1 "use client";
2 import { useEffect, useState } from "react";
3
4 export default function ClientComponent() {
5 const [data, setData] = useState(null);
6
7 useEffect(() => {
8 fetch("/api/hello")
9 .then((res) => res.json())
10 .then(setData);
11 }, []);
12
13 if (!data) return <div>Loading...</div>;
14 return <div>{data.message}</div>;
15 }

5. API Routes (Route Handlers)


Create backend endpoints in app/api/ for use by client or
server components.
Example

1 // app/api/hello/route.js
2 export async function GET(request) {
3 return Response.json({ message: "Hello from API"
});
4 }

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

6. Revalidating Data (ISR)


Use revalidate option to update static data at intervals.

Example

1 // app/page.js
2 export const revalidate = 60; // Revalidate every
60 seconds
3
4 export default async function Page() {
5 const res = await
fetch("https://api.example.com/data");
6 const data = await res.json();
7 return <div>{data.message}</div>;
8 }

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

7. Parallel & Sequential Fetching


Fetch multiple resources in parallel or sequence.

Examples

1 // Parallel
2 const [postsRes, usersRes] = await Promise.all([
3 fetch("https://api.example.com/posts"),
4 fetch("https://api.example.com/users"),
5 ]);
6 const posts = await postsRes.json();
7 const users = await usersRes.json();
8
9 // Sequential
10 const res = await
fetch("https://api.example.com/first");
11 const first = await res.json();
12 const res2 = await
fetch(`https://api.example.com/second?
id=${first.id}`);
13 const second = await res2.json();

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

8. Error Handling
Handle errors in server and client components.

Examples

1 // Server component
2 export default async function Page() {
3 try {
4 const res = await
fetch("https://api.example.com/data");
5 if (!res.ok) throw new Error("Failed to
fetch");
6 const data = await res.json();
7 return <div>{data.message}</div>;
8 } catch (err) {
9 return <div>Error: {err.message}</div>;
10 }
11 }
12
13 // Client component
14 "use client";
15 import { useEffect, useState } from "react";
16 export default function ClientComponent() {
17 const [data, setData] = useState(null);
18 const [error, setError] = useState(null);
19 useEffect(() => {
20 fetch("/api/hello")
21 .then(res => res.json())
22 .then(setData)
23 .catch(setError);
24 }, []);
25 if (error) return <div>Error: {error.message}
</div>;
26 if (!data) return <div>Loading...</div>;
27 return <div>{data.message}</div>;
28 }

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

SSR vs SSG vs ISR vs CSR


A quick comparison of the main data fetching/rendering
strategies in Next.js:

When How Data Use Case / Example


Pattern
Rendered is Fetched Pros Usage

export const

dynamic =

SSR (Server- At request "force-


On every Always up-to-
Side time dynamic"
request date, dynamic
Rendering) (server) fetch(..., {

cache: "no-

store" })

SSG (Static At build time At build Fast, cached, Default fetch in

Site (or on- time good for static server

Generation) demand) (server) content components

ISR Static speed,


At build time At build export const
(Incremental but can
+ revalidated time, then revalidate =
Static update after
on interval revalidated 60
Regeneration) deploy

Dynamic UI, useEffect +


CSR (Client- In the After page
user-specific fetch in
Side browser loads
data, client
Rendering) (client) (client)
interactivity components

thedevspace.io
TheDevSpace | Full-Stack Web Development Course

Summary Table

Data
Strategy Rendered Example
Fetch

dynamic =
Server, per Server, per
SSR "force-
request request
dynamic"

Default async
Server, at Server, at
SSG server
build build
component

Server, at Server, at
revalidate =
ISR build + build +
60
revalidate interval

useEffect in
Client, after Client,
CSR client
load after load
component

When to use which?

SSR: Dynamic data, SEO, always up-to-date (e.g.


dashboards, user pages)
SSG: Static content, blogs, docs, marketing pages

ISR: Static content that updates periodically (e.g. product


listings)
CSR: Highly interactive, user-specific, or real-time data (e.g.
dashboards, chat)

thedevspace.io

You might also like