Client components are used when you need interactivity, such as handling user input events like clicks or typing. Server components are better for static or server-only tasks like data fetching or SEO metadata.
Server components run only on the server and cannot handle client-side events like clicks. Therefore, the button will not respond to clicks if the handler is in a server component.
import React from 'react'; // Component code here
In Next.js 14+, adding the directive "use client"; at the top of the file marks the component as a client component. Other options are either invalid or do not mark the component correctly.
"use client"; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }
The component uses React's useState hook to track count. Each button click increments count by 1. After two clicks, count becomes 2 and is displayed.
import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </> ); }
Without the "use client" directive, Next.js treats the component as a server component, which cannot use hooks like useState or handle client events. Adding "use client" fixes this.