0
0
NextJSframework~5 mins

Client component boundaries in NextJS

Choose your learning style9 modes available
Introduction

Client component boundaries tell Next.js which parts of your app run in the browser. This helps separate server work from interactive UI work.

When you want a part of your page to respond to user clicks or input.
When you need to use browser-only features like local storage or event listeners.
When you want to add animations or dynamic updates without reloading the page.
When you want to keep server code and client code clearly separated for better performance.
Syntax
NextJS
"use client";  // at the top of your component file

export default function MyComponent() {
  // client-side code here
}

Place "use client"; at the very top of your component file to mark it as a client component.

Without this directive, components are server components by default in Next.js 13+.

Examples
This client component uses React state and handles a button click.
NextJS
"use client";

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
This component is a server component because it lacks the "use client"; directive.
NextJS
export default function ServerOnly() {
  return <p>This is a server component by default.</p>;
}
Marking with "use client"; allows use of browser-only features.
NextJS
"use client";

export default function ClientOnlyFeature() {
  // You can use browser APIs here
  return <p>Runs only in the browser.</p>;
}
Sample Program

This client component counts how many times the button is clicked. It uses React's useState hook and runs only in the browser because of the "use client"; directive.

The button has an accessible label for screen readers.

NextJS
"use client";

import { useState } from 'react';

export default function ClickCounter() {
  const [clicks, setClicks] = useState(0);

  return (
    <main>
      <h1>Click Counter</h1>
      <button onClick={() => setClicks(clicks + 1)} aria-label="Increment counter">
        Clicked {clicks} times
      </button>
    </main>
  );
}
OutputSuccess
Important Notes

Always put "use client"; at the very top of the file, before imports.

Client components can import other client components or server components, but server components cannot import client components.

Use client components only when you need interactivity or browser APIs to keep your app fast.

Summary

Client component boundaries tell Next.js which parts run in the browser.

Mark client components with "use client"; at the top of the file.

Use client components for interactivity and browser-only features.