Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NX
Next.js
0/10 completed
Beginner
Why Next.js?Pages, layouts and routingLinks, images and fonts
Intermediate
Server and Client ComponentsFetching data and streamingRoute Handlers (API routes)Forms and Server Actions
Advanced
Caching and revalidationMetadata, SEO, errors and Proxy
Pro
Auth, deployment and production
Tracks / Next.js / Intermediate

Fetching data and streaming

In the App Router, most data fetching happens in Server Components, with plain async/await. No useEffect, no loading state juggling, no extra API layer for reads.

Fetching in a Server Component

tsx
// app/blog/page.tsx
type Post = { id: number; title: string };

export default async function BlogPage() {
  const res = await fetch('https://api.example.com/posts');
  if (!res.ok) throw new Error('Failed to load posts');   // caught by the nearest error.tsx
  const posts: Post[] = await res.json();

  return (
    <ul>
      {posts.map((post) => <li key={post.id}>{post.title}</li>)}
    </ul>
  );
}

You can also query a database or ORM directly:

tsx
import { db } from '@/lib/db';

export default async function Page() {
  const users = await db.user.findMany({ take: 10 });
  return <p>{users.length} users</p>;
}

Good to know: in Next.js 16, fetch results are not cached by default. Each request gets fresh data. You opt into caching explicitly with 'use cache' (see the Caching lesson).

Avoid waterfalls: fetch in parallel

Sequential awaits add up. If the requests are independent, start them together:

tsx
export default async function Dashboard() {
  // ✗ Sequential: total time = user + orders + stats
  // const user = await getUser(); const orders = await getOrders(); ...

  // ✓ Parallel: total time = the slowest one
  const [user, orders, stats] = await Promise.all([getUser(), getOrders(), getStats()]);
  return <h1>Hi {user.name}: {orders.length} orders, {stats.visits} visits</h1>;
}

Streaming with loading.tsx

Add a loading.tsx next to a page to show an instant loading state while the page's data loads. The layout stays visible and interactive:

tsx
// app/blog/loading.tsx
export default function Loading() {
  return <p>Loading posts…</p>;   // or a skeleton UI
}

Behind the scenes, Next.js wraps your page in a React <Suspense> boundary with this as the fallback.

Granular streaming with <Suspense>

Show the fast parts of a page immediately, and stream slow parts in as they finish:

tsx
import { Suspense } from 'react';

export default function ProductPage() {
  return (
    <>
      <ProductDetails />                                  {/* fast: shows immediately */}
      <Suspense fallback={<p>Loading reviews…</p>}>
        <Reviews />                                       {/* slow: streams in when ready */}
      </Suspense>
      <Suspense fallback={<p>Loading recommendations…</p>}>
        <Recommendations />
      </Suspense>
    </>
  );
}

async function Reviews() {
  const reviews = await getReviews();                     // takes 2 seconds
  return <ul>{reviews.map((r) => <li key={r.id}>{r.text}</li>)}</ul>;
}

Here's the same behaviour simulated in the browser with React's use hook and Suspense:

Meaningful loading states: prefer skeletons that match the final layout over generic spinners, so the page doesn't jump when the content arrives.

Runtime data: cookies, headers and searchParams

APIs that depend on the incoming request make a component render per request. Wrap such components in <Suspense> so the rest of the page can still be pre-rendered:

tsx
import { cookies } from 'next/headers';
import { Suspense } from 'react';

async function Greeting() {
  const theme = (await cookies()).get('theme')?.value ?? 'light';   // cookies() is async
  return <p>Your theme: {theme}</p>;
}

export default function Page() {
  return (
    <>
      <h1>Dashboard</h1>
      <Suspense fallback={<p>Loading…</p>}>
        <Greeting />
      </Suspense>
    </>
  );
}

Client-side fetching (when you need it)

For data that changes constantly while the user is on the page (live search, polling, infinite scroll), fetch in a Client Component with a library like SWR or TanStack Query:

tsx
'use client';
import useSWR from 'swr';

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export function Notifications() {
  const { data, error, isLoading } = useSWR('/api/notifications', fetcher, { refreshInterval: 5000 });
  if (isLoading) return <p>Loading…</p>;
  if (error) return <p>Failed to load</p>;
  return <p>{data.unread} unread</p>;
}

Practice (in your project)

  1. Build /posts, which fetches 10 posts from https://jsonplaceholder.typicode.com/posts in a Server Component.
  2. Add a loading.tsx with a skeleton list.
  3. On /posts/[id], fetch the post and its comments in parallel with Promise.all, and stream the comments with <Suspense>.
✎ Check your understanding

1.Where is data usually fetched in the App Router?

2.What does wrapping a slow component in <Suspense fallback={...}> do?

← Server and Client Components
React · live preview
Preview