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.
Use client directive in 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.
useState to track clicks, so it needs the use client directive."use client"; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
"use client"; export default function Greeting() { return <h1>Hello from the client!</h1>; }
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.
"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> ); }
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.
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.