Client components handle interactivity because they run in the browser where users click, type, and interact. This lets the page respond quickly without waiting for the server.
0
0
Why client components handle interactivity in NextJS
Introduction
When you want buttons to respond immediately when clicked.
When you need to update parts of the page based on user input.
When showing or hiding content dynamically without reloading the page.
When you want to keep track of user actions like form filling.
When you want smooth animations or effects triggered by user actions.
Syntax
NextJS
// In Next.js, add 'use client' at the top of your component file 'use client'; import { useState } from 'react'; export default function InteractiveButton() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ); }
The 'use client' directive tells Next.js this component runs in the browser.
Client components can use React hooks like useState to manage interactive state.
Examples
This example shows a button that toggles text visibility when clicked.
NextJS
'use client'; import { useState } from 'react'; export default function ToggleText() { const [show, setShow] = useState(false); return ( <> <button onClick={() => setShow(!show)}> {show ? 'Hide' : 'Show'} Text </button> {show && <p>This text appears when you click Show.</p>} </> ); }
This example updates the displayed text as the user types in the input box.
NextJS
'use client'; import { useState } from 'react'; export default function InputMirror() { const [text, setText] = useState(''); return ( <> <input type="text" value={text} onChange={e => setText(e.target.value)} aria-label="Type something" /> <p>You typed: {text}</p> </> ); }
Sample Program
This is a simple interactive counter. Each click updates the number shown immediately in the browser.
NextJS
'use client'; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <main style={{ padding: '1rem', fontFamily: 'Arial, sans-serif' }}> <h1>Simple Counter</h1> <button onClick={() => setCount(count + 1)} aria-label="Increase count" style={{ padding: '0.5rem 1rem', fontSize: '1rem', cursor: 'pointer', borderRadius: '0.25rem', border: '1px solid #333', backgroundColor: '#f0f0f0' }} > Click me </button> <p>You clicked {count} times.</p> </main> ); }
OutputSuccess
Important Notes
Without 'use client', components run on the server and cannot handle user clicks or typing.
Client components increase page interactivity and improve user experience by responding instantly.
Summary
Client components run in the browser to handle user actions like clicks and typing.
Use 'use client' at the top of your component file to make it interactive.
Client components can use React hooks like useState to manage changing data.