0
0
NextJSframework~5 mins

When to use client components in NextJS

Choose your learning style9 modes available
Introduction

Client components let your app respond quickly to user actions by running code in the browser. They help make your pages interactive and dynamic.

When you need buttons or forms that users can click or type in.
When you want to update parts of the page without reloading it.
When you use browser-only features like local storage or animations.
When you want to handle user input or events like clicks and typing.
When you need to show changing data that updates on the screen immediately.
Syntax
NextJS
"use client";

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

Start the file with "use client"; to mark it as a client component.

Client components can use React hooks like useState and useEffect.

Examples
This client component shows a button that updates the count when clicked.
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 client component shows the current time and updates it every second.
NextJS
"use client";

import { useEffect, useState } from 'react';

export default function Time() {
  const [time, setTime] = useState(new Date().toLocaleTimeString());

  useEffect(() => {
    const timer = setInterval(() => {
      setTime(new Date().toLocaleTimeString());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return <p>Current time: {time}</p>;
}
Sample Program

This client component shows a button that toggles a message on and off. It uses state and event handling in the browser.

NextJS
"use client";

import { useState } from 'react';

export default function ToggleMessage() {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(!show)} aria-pressed={show} aria-label="Toggle message">
        {show ? 'Hide' : 'Show'} Message
      </button>
      {show && <p>Hello! This message appears when you click the button.</p>}
    </div>
  );
}
OutputSuccess
Important Notes

Client components run in the browser, so they can access browser APIs like window and document.

Use client components only when you need interactivity to keep your app fast and efficient.

Server components are better for static content that does not change on the client.

Summary

Client components make your app interactive by running in the browser.

Use them for buttons, forms, animations, and anything that changes on user actions.

Mark files with "use client"; to create client components in Next.js.