Async Components
Part of the Next.js Essentials section of Coddy's React journey — lesson 23 of 47.
Here is the payoff for everything the last chapter set up. A server component can be async:
import { getDishes } from '../lib/data';
export default async function Page() {
const dishes = await getDishes();
return <h1>{dishes.length} dishes</h1>;
}Read that again, because it is genuinely new. The component waits. Next.js runs it on the server, lets the await finish, and only then turns the result into HTML.
Compare it to the browser-only version you'd otherwise write:
- The page renders empty first
- A request goes out after the page has loaded
- Some state flips, and the content appears, a flicker the user sees every time
With an async server component there is no first empty render. There is nothing to flicker into, because the data was already there when the HTML was built. No useEffect, no loading flag, no second request.
Two rules make this legal:
- Only server components may be
async: a component marked'use client'may not - The data has to come from somewhere the server can reach: a database, a file, or a module like
lib/data.js
Challenge
Easylib/data.js is provided and locked. It exports getDishes(), which returns a promise for an array of { id, name } objects.
- Make
Pageinapp/page.jsxanasyncfunction. await getDishes()into adishesvariable.- Inside
<ul id="dish-list">, render one<li>per dish, withkey={dish.id},id={dish.id}and the dish'snameas its text.
No useEffect, no loading flag, just await.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing5Data on the Server
Async ComponentsAwaiting Route ParamsTwo Fetches at OnceLoading StatesHandling ErrorsRecap: Data Fetching