0
0
NextjsConceptBeginner · 3 min read

What is use client in Next.js: Explanation and Example

use client is a directive in Next.js that marks a component to run on the client side instead of the server. It enables React features like state and effects that only work in the browser. Without it, components are rendered on the server by default in Next.js 13+.
⚙️

How It Works

Next.js 13 introduced a new way to build apps using Server Components by default. This means components render on the server to improve performance and SEO. But some parts of your app need to run in the browser, like interactive buttons or forms.

To tell Next.js that a component should run in the browser, you add "use client" at the top of the file. Think of it like putting a "This part needs to be done on your computer" sticker on that component. This lets React know to include browser-only features like state, event handlers, and effects.

Without "use client", components are treated as server components and cannot use hooks like useState or useEffect. This separation helps Next.js optimize loading and rendering.

💻

Example

This example shows a simple counter button that works only on the client side. The "use client" directive enables React state and interaction.

javascript
"use client";

import { useState } from 'react';

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}
Output
A button labeled 'Clicked 0 times' that increments the number each time it is clicked.
🎯

When to Use

Use "use client" when your component needs to:

  • Handle user interactions like clicks or form inputs.
  • Use React hooks such as useState, useEffect, or useContext.
  • Access browser-only APIs like window or localStorage.

For example, interactive UI elements, animations, or components that update dynamically based on user input should be client components. Static content or data fetching can stay as server components for better performance.

Key Points

  • Default: Components are server-rendered unless marked with "use client".
  • Directive: "use client" must be the first line in the component file.
  • Enables: React hooks and browser APIs inside the component.
  • Performance: Use client components only when needed to keep app fast.

Key Takeaways

"use client" marks a Next.js component to run in the browser, enabling React hooks and interactivity.
Without "use client", components render on the server by default in Next.js 13+.
Use it only for components that need state, effects, or browser APIs to keep your app fast.
"use client" must be the very first line in the component file.
This directive helps Next.js optimize rendering by separating server and client logic.