Next.jsMedium

Can Client Components be async?

No. Client Components cannot be async functions; React does not support async components in the browser and logs an error. Only Server Components can be async. In a Client Component, read async data with React's use(promise) inside <Suspense>, a data library, or an effect.

Why

An async component returns a Promise. On the server, React can await it once and stream the result. In the browser, components re-render often, and creating a new promise on every render would cause infinite suspension and refetching.

What to do instead

  1. Pass a promise from a Server Component and call use(promise) in the Client Component. The promise is created once on the server, so it is stable.
  2. Use SWR or TanStack Query (useSWR, useSuspenseQuery), which cache the promise for you.
  3. useEffect + state for simple cases, with cleanup to avoid race conditions.
  4. Restructure: move the data fetching into a parent Server Component and pass the data as props.

Pitfall with use()

Do not create the promise inside the Client Component during render, such as use(fetch(url)). Each render creates a new promise and the component suspends forever. The promise must come from a cache, a parent, or a library.

Related

Client Components can call Server Functions (which are async) from event handlers or transitions. That is a function call, not an async component.

Code example

tsx
1// app/comments/page.tsx - Server Component creates the promise once
2import { Suspense } from "react";
3import { Comments } from "./comments";
4import { getComments } from "@/lib/comments";
5
6export default function Page() {
7 const commentsPromise = getComments(); // not awaited
8 return (
9 <Suspense fallback={<p>Loading comments…</p>}>
10 <Comments commentsPromise={commentsPromise} />
11 </Suspense>
12 );
13}
14
15// app/comments/comments.tsx
16// "use client";
17// import { use, useState } from "react";
18//
19// // export default async function Comments() {} <- not allowed in a Client Component
20// export function Comments({ commentsPromise }: { commentsPromise: Promise<{ id: string; text: string }[]> }) {
21// const comments = use(commentsPromise); // suspends until resolved
22// const [open, setOpen] = useState(true);
23// return open ? <ul onClick={() => setOpen(false)}>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul> : null;
24// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app