Client Components run in the browser and are ideal for fetching data based on user interactions. Unlike Server Components, they fetch data on the client-side after the initial render, making them well-suited for dynamic, interactive features.
Client-Side Execution:
Runs in the browser, allowing access to browser APIs like window
, document
, and localStorage
.
Data Fetching:
Use React’s useEffect()
hook to initiate data requests after the component mounts or in response to user actions.
User Interaction:
Often triggered by events such as button clicks or form submissions, which can provide a more dynamic experience.
In this example, the component fetches data from an API after mounting. If the data isn’t available yet, a loading message is displayed.
"use client";
import { useEffect, useState } from "react";
export default function DashboardClient() {
const [data, setData] = useState<{ title: string } | null>(null);
useEffect(() => {
// Fetch data when the component mounts.
fetch("<https://api.example.com/data>")
.then((res) => res.json())
.then((json) => setData(json))
.catch((error) => console.error("Fetch error:", error));
}, []);
if (!data) {
return <p>Loading...</p>;
}
return (
<section>
<h1>Data: {data.title}</h1>
</section>
);
}
User-Initiated Data:
For scenarios where data should load after a user action (e.g., clicking a button or submitting a form).
Non-Critical SEO Data:
When the data isn’t essential for search engine indexing, as initial renders may be empty until the fetch completes.
Reducing Server Load:
Offload data fetching to the client to decrease the number of server requests.
Interactive Experience:
Enables dynamic updates and interactivity based on user events.
Access to Browser APIs:
Since it runs on the client, you can directly use browser-specific features.
Reduced Server Demand:
Shifts the responsibility of data fetching to the client, which can help in scaling server resources.
Initial Render Without Data:
The first render may display a loading state until the fetch completes.
SEO Considerations:
Since data is loaded client-side, search engines might not see the updated content, affecting SEO.