Next.jsEasy
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/awaitdirectly 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(). useIdworks, since it is pure.
Replacements
| Client pattern | Server pattern |
|---|---|
useEffect + fetch | await fetch() in the component |
useContext for config | import a module or pass props |
useState for form result | Server 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 Component2import { cookies } from "next/headers";3import { cache } from "react";4import { db } from "@/lib/db";5import { EditNameButton } from "./edit-name-button"; // "use client": uses useState67const getProfile = cache(async (id: string) => db.user.findUnique({ where: { id } }));89export default async function Profile() {10 // const [x, setX] = useState(0); // Error: hooks need a Client Component11 const userId = (await cookies()).get("uid")?.value; // allowed: server function12 const profile = userId ? await getProfile(userId) : null; // allowed: await + cache1314 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.