-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreaming-and-suspense-in-next13.js
More file actions
99 lines (77 loc) · 2.48 KB
/
streaming-and-suspense-in-next13.js
File metadata and controls
99 lines (77 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// File: streaming-and-suspense-in-next13.js
/*
📘 Topic: Streaming and Suspense in Next.js 13+
Next.js App Router (v13+) brings full support for React Server Components,
Streaming UI, and the Suspense mechanism. These help build faster, progressive UIs.
*/
////////////////////////
// ⛲ 1. What is Streaming?
////////////////////////
/*
✅ Enables sending parts of the UI to the browser *as soon as they're ready*
✅ Improves perceived performance and TTFB (time to first byte)
✅ Powered by React Server Components and `Suspense`
✅ No need to wait for entire page to be ready
Think: shell renders instantly → slow parts stream in later (like charts or user data)
*/
////////////////////////
// ⏳ 2. Suspense in App Router
////////////////////////
/*
✅ React’s built-in component to “suspend” part of the UI
✅ You can wrap server components or async logic
✅ Next.js handles it on the server — streamed progressively to client
⚠️ In App Router, Suspense works by default with server components.
*/
import { Suspense } from 'react';
function SlowComponent() {
// Simulate delay
const data = fetch('https://dummyjson.com/users/1').then(res => res.json());
throw data; // Suspense will catch and wait
}
function LoadingFallback() {
return <p>⏳ Loading user data...</p>;
}
export default function Page() {
return (
<div>
<h1>Streaming + Suspense Demo</h1>
{/* ⚙️ Part below will stream in once ready */}
<Suspense fallback={<LoadingFallback />}>
<SlowComponent />
</Suspense>
</div>
);
}
////////////////////////
// ⚙️ 3. Streaming in App Directory
////////////////////////
/*
✅ Any `page.js`, `layout.js`, or nested component can use `Suspense`
✅ Even layouts can “stream” child segments (great for dashboards or feeds)
📁 Example structure:
- app
- layout.js
- dashboard
- layout.js
- analytics
- page.js
💡 Nested layouts can individually use Suspense — no need to wait for whole page
*/
////////////////////////
// 📌 Tips and Summary
////////////////////////
/*
✅ Use Suspense for:
- Slow server components (e.g. DB reads, APIs)
- Third-party libraries (charts, auth, etc.)
- Code-splitting (dynamic imports)
✅ Streaming improves UX:
- First paint faster
- Avoids big loading skeletons
- Enables partial hydration
🎯 TL;DR:
- Suspense pauses rendering for async parts
- Streaming sends what’s ready immediately
- Together = snappy, progressive React apps in Next 13+
*/