Keep Client Parts Small
Part of the Next.js Essentials section of Coddy's React journey — lesson 20 of 47.
When a page needs one interactive button, there's a tempting shortcut: slap 'use client' at the top of the page and move on. It works. It's also the most common way to throw away everything Next.js just gave you.
Remember rule 2: the directive marks the whole file. Mark the page and the heading, the description, the list of dishes and every component they render all become client code, downloaded and re-run in the browser. One button dragged the whole page across the boundary.
The habit that fixes this is small and mechanical:
Push
'use client'down to the leaves.
Pull the interactive bit into its own small file, mark that file, and let the page stay on the server:
// app/page.jsx - still a server component
import LikeButton from '../components/LikeButton';
export default function Home() {
return (
<main>
<h1>Coddy Eats</h1>
<LikeButton />
</main>
);
}Two things to notice. First, a server component can render a client component: that direction is completely normal. Second, the page didn't change shape; only one small piece moved.
There's a second error that pushes you toward the same habit. Put an onClick straight onto a button in a server component and the runtime stops you: Event handlers cannot be passed to Client Component props. A handler is a function: it can't survive the trip to the browser unless it lives in a client file.
Challenge
EasyThis page puts an onClick on a button inside a server component, so the app won't render at all.
Fix it without marking the page as a client component:
- In
components/LikeButton.jsx, write a client component ('use client'on line 1) that holds a like count in state and renders a button withid="like". Its text must beLikes:followed by the count. - In
app/page.jsx, delete the broken button and render<LikeButton />instead. Import it from'../components/LikeButton'. - Leave the heading and the tagline exactly as they are: the page must stay a server component.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
4Server & Client
Two Kinds of ComponentReading the ErrorThe 'use client' LineKeep Client Parts SmallServer Inside ClientRecap: Server & Client