CHAPTER 1What are Client Components
Client Components are React components that paint by replacing the DOM in the client, so their Javascript code has to be sent over the line. In NextJS, though, you have to explicitly mark them as such with a special instruction, since NextJS assumes that components are server by default:
"use client";
This directive has to be at the top of a file which describes a Client Component.
Import transitivity
The "use client"
mark will affect the Client Component and all files loaded
from the Client Component using import
, so a whole branch of the module graph
is affected.
Since Server Components are the default, all components are part of the Server
Component module graph unless defined or imported in a module that starts with
the "use client"
directive.
When to use Client Components
Anywhere you need to store some state on the client, something you are changing or might change quickly ("editors", forms, loading things).
A good list of cases is:
- You need interactivity (
onClick
,onChange
, etc.) - You have state or "effects" (
useState
,useEffect
, etc.) - You use Browser only APIs (
WebGL
,Audio Output
,Keyboard
, etc.) - You use React
class
components (old-style components written long ago).