0
0
NextjsConceptBeginner · 3 min read

What is Client Component in Next.js: Simple Explanation and Example

In Next.js, a client component is a React component that runs entirely in the browser, enabling interactive features like state and event handling. You mark it with 'use client' at the top of the file to tell Next.js to render it on the client side instead of the server.
⚙️

How It Works

Think of a client component as a part of your webpage that lives and works inside the user's browser. Unlike server components that prepare HTML on the server, client components handle things like clicks, typing, and animations directly on the user's device.

When you add 'use client' at the top of a React component file in Next.js, you tell the framework to send this component's code to the browser. This allows the component to use React features like state and effects, which need to run where the user interacts.

Imagine a remote control car: the server builds the track (server components), but the client component is the remote control that lets you drive the car in real time.

💻

Example

This example shows a simple client component that counts how many times a button is clicked. It uses React state and runs in the browser.

javascript
'use client';

import { useState } from 'react';

export default function ClickCounter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
Output
You clicked 0 times [Button labeled 'Click me']
🎯

When to Use

Use client components when you need interactivity on your page, such as buttons, forms, animations, or any feature that changes after the page loads. They are perfect for parts of your app that respond to user actions.

For example, a shopping cart button that updates the number of items, a dropdown menu, or a live chat widget should be client components. Meanwhile, static content like headers or footers can stay as server components for faster loading.

Key Points

  • Client components run in the browser and support React state and events.
  • Mark a component with 'use client' at the top to make it a client component.
  • Use client components for interactive UI parts that need user input or dynamic updates.
  • Server components are better for static content to improve performance.

Key Takeaways

Client components run in the browser and handle interactivity using React state and events.
Add 'use client' at the top of a file to make a React component a client component in Next.js.
Use client components for buttons, forms, and dynamic UI that reacts to user actions.
Keep static parts of your page as server components for better performance.