Can Server Components use hooks?

Server Components cannot use stateful or effect hooks such as useState, useEffect, useReducer, useContext or useRef, because they render once on the server and never re-render in the browser. They can use React's use() and cache(), and Next.js server functions like cookies() and headers().

Not allowed

  • useState, useReducer: no state on the server.
  • useEffect, useLayoutEffect: no lifecycle after render.
  • useContext: Server Components cannot read React context.
  • Custom hooks that call any of those, and Next.js client hooks (useRouter, usePathname, useSearchParams).

Using them gives an error such as "You're importing a component that needs useState. This React Hook only works in a Client Component."

Allowed

  • async/await directly in the component, which replaces most data hooks.
  • use(promise), though awaiting is simpler in a Server Component.
  • React.cache() for per-request memoization.
  • Next.js functions: cookies(), headers(), draftMode(), connection(), after(), notFound(), redirect(), cacheLife(), cacheTag().
  • useId works, since it is pure.

Replacements

Client patternServer pattern
useEffect + fetchawait fetch() in the component
useContext for configimport a module or pass props
useState for form resultServer Function + useActionState in a small Client Component

Tip

Need interactivity in one part of a server-rendered page? Extract just that part into a Client Component.

Code example

tsx
1// app/profile/page.tsx - Server Component
2import { cookies } from "next/headers";
3import { cache } from "react";
4import { db } from "@/lib/db";
5import { EditNameButton } from "./edit-name-button"; // "use client": uses useState
6
7const getProfile = cache(async (id: string) => db.user.findUnique({ where: { id } }));
8
9export default async function Profile() {
10 // const [x, setX] = useState(0); // Error: hooks need a Client Component
11 const userId = (await cookies()).get("uid")?.value; // allowed: server function
12 const profile = userId ? await getProfile(userId) : null; // allowed: await + cache
13
14 if (!profile) return <p>Please sign in.</p>;
15 return (
16 <section>
17 <h1>{profile.name}</h1>
18 <EditNameButton initialName={profile.name} />
19 </section>
20 );
21}

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