0
0
NextJSframework~5 mins

Use client directive in NextJS

Choose your learning style9 modes available
Introduction

The use client directive tells Next.js that a component should run in the browser, not on the server. This helps Next.js know where to render your code.

When you want to use React hooks like <code>useState</code> or <code>useEffect</code> that only work in the browser.
When your component needs to respond to user actions like clicks or typing.
When you want to access browser-only APIs like <code>window</code> or <code>localStorage</code>.
When you want to add animations or interactive UI elements that need client-side rendering.
Syntax
NextJS
"use client";

export default function MyComponent() {
  // component code here
}

The directive must be the very first line in your component file.

It is a plain string, not a function or import.

Examples
This component uses useState to track clicks, so it needs the use client directive.
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>
  );
}
A simple client component that renders a greeting message.
NextJS
"use client";

export default function Greeting() {
  return <h1>Hello from the client!</h1>;
}
Sample Program

This component shows a button that toggles between ON and OFF states when clicked. It uses useState, so it must run on the client. The aria-pressed attribute helps screen readers understand the toggle state.

NextJS
"use client";

import { useState } from 'react';

export default function Toggle() {
  const [isOn, setIsOn] = useState(false);

  return (
    <button onClick={() => setIsOn(!isOn)} aria-pressed={isOn}>
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}
OutputSuccess
Important Notes

Without use client, React hooks like useState will cause errors because they only work in the browser.

Server components are faster but cannot handle user interactions directly.

Use use client only when needed to keep your app fast and efficient.

Summary

Use the use client directive to mark components that need to run in the browser.

Place it as the first line in your component file.

Use it when your component uses React hooks or browser APIs.