Next.js
/Beginner
Client Components
Definition
Traditional React components that are sent over the network and executed in the user's browser, allowing for interactivity, state, and browser APIs.
Explain Like I'm New
If you need a button to do something when clicked (`onClick`), if you need to track a value changing (`useState`), or if you need to access the window object (`window.localStorage`), you MUST use a Client Component.
Real World Example
A `<ThemeToggle>` switch. It needs an `onClick` listener to toggle between light/dark mode, and it needs `localStorage` to save the preference. It must be a Client Component.
Common Use Cases
- •Interactivity (buttons, forms)
- •State management
- •React lifecycle hooks
- •Browser API access
Interactive Example
// MUST be the very first line to opt-in to client-side interactivity 'use client'; import { useState } from 'react'; export default function LikeButton() { // We can safely use State here! const [likes, setLikes] = useState(0); return ( <button onClick={() => setLikes(l => l + 1)} // We can safely use onClick here! className="bg-red-500 text-white p-2 rounded" > ❤️ {likes} </button> ); }
Interview Questions
basic
- What directive must you add to the top of a file to turn it into a Client Component?
intermediate
- Is a Client Component ONLY rendered on the client browser in Next.js?