0
0
NextJSframework~30 mins

When to use client components in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
When to Use Client Components in Next.js
📖 Scenario: You are building a simple Next.js app that shows a greeting message and a button to toggle the greeting text color. The greeting text color changes only when the user clicks the button.
🎯 Goal: Build a Next.js component that uses a client component to handle user interaction (button click) and state (color toggle) while the rest of the page remains server-rendered.
📋 What You'll Learn
Create a server component that renders a greeting message
Create a client component that toggles the greeting text color on button click
Use React useState hook inside the client component
Use the client component inside the server component
Add a button with an accessible aria-label for toggling color
💡 Why This Matters
🌍 Real World
Many Next.js apps use server components for fast loading and client components for interactive parts like buttons, forms, and toggles.
💼 Career
Understanding when to use client components is essential for building efficient, accessible, and maintainable Next.js applications.
Progress0 / 4 steps
1
Create the Server Component with Greeting Text
Create a server component called GreetingServer that returns a <div> with the text Hello from Server Component! inside a <p> tag.
NextJS
Need a hint?

Server components do not use hooks or client-side state.

2
Create the Client Component with Color Toggle State
Create a client component called ColorToggle that uses useState to toggle a boolean state called isRed starting as false. The component should return a <p> with text Color toggled! styled with red color if isRed is true, otherwise black. Also add a <button> with aria-label="Toggle color" that toggles isRed when clicked.
NextJS
Need a hint?

Client components must start with "use client"; at the top.

3
Import and Use Client Component inside Server Component
Update GreetingServer to render <ColorToggle /> below the greeting text inside the <div>.
NextJS
Need a hint?

Client components can be imported and used inside server components like normal React components.

4
Add Accessibility and Final Touches
Ensure the button in ColorToggle has an aria-label="Toggle color" attribute for accessibility. Also, add a tabIndex="0" to the button to allow keyboard navigation.
NextJS
Need a hint?

Adding tabIndex={0} makes the button reachable by keyboard users.