Next.jsEasy
When should you use the 'use client' directive?
Add "use client" at the top of a file when the component needs interactivity or browser-only features: state, effects, event handlers, context, browser APIs, or a library that relies on them. Place it as low in the tree as possible, because it turns that module and everything it imports into client code.
You need it for
useState,useReducer,useEffect,useLayoutEffect,useReffor DOM work.- Event handlers:
onClick,onChange,onSubmitwith client logic. - Context providers and consumers (
createContext,useContext). - Browser APIs:
window,localStorage,IntersectionObserver, geolocation. - Client hooks from Next.js:
useRouter,usePathname,useSearchParams,useParams,useLinkStatus. - React hooks like
useActionState,useOptimistic,useFormStatus. - Third-party UI libraries that use hooks but lack the directive (wrap them in your own
"use client"file).
You do not need it for
- Fetching data, reading cookies or headers, or rendering static markup.
- Calling a Server Function from a
<form action>; forms work in Server Components. - Every child of a Client Component; only the entry point needs the directive.
What it actually does
It marks a module boundary. The file and its imports are bundled for the browser. Components are still server-side rendered to HTML on first load, then hydrated.
Pitfalls
- Adding it to
app/layout.tsxor a page out of habit makes the whole subtree client-side. - Props crossing the boundary must be serializable; you cannot pass a regular function from a Server Component.
- Secrets read in a client module are
undefined(or leaked if prefixedNEXT_PUBLIC_).
Code example
tsx
1// app/components/theme-toggle.tsx2"use client"; // needs state, an event handler and localStorage34import { useEffect, useState } from "react";56export function ThemeToggle() {7 const [dark, setDark] = useState(false);89 useEffect(() => {10 setDark(localStorage.getItem("theme") === "dark");11 }, []);1213 function toggle() {14 const next = !dark;15 setDark(next);16 localStorage.setItem("theme", next ? "dark" : "light");17 document.documentElement.classList.toggle("dark", next);18 }1920 return <button onClick={toggle}>{dark ? "🌙" : "☀️"}</button>;21}2223// app/layout.tsx stays a Server Component and just renders <ThemeToggle />
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.