Skip to main content

Client

Client Components enable you to add client-side interactivity to your application. In Next.js, they are prerendered on the server and hydrated on the client. You can think of Client Components as how Next.js 12 and previous versions worked (i.e. the pages/ directory).

Fetching data in the client - Next.js 13.2

A component becomes a Client Component when using the "use client" directive at the top of the file (before any imports).

These components (and files) can be placed anywhere inside your application. They do not need to be in app/, specifically.

For example, you might want a components/ directory. However, the app/ directory enables you to colocate components with pages, which was not previously possible in the pages/ directory.

tip

Good to know: Previous Next.js data fetching methods such as getServerSideProps, getStaticProps, and getInitialProps are not supported in the new app directory.

fetchting data in Client Components

Although it's possible to fetch data in Client Components, we recommend fetching data in Server Components unless you have a specific reason for fetching data on the client. Moving data fetching to the server leads to better performance and user experience.

// It uses the fetch API to fetch data from the API
// It uses the useSWR hook from the SWR library to fetch data from the API
// the fetch api is now available in client componets in nextjs 13

"use client";

import React, { Suspense } from "react";
import Link from "next/link";
import useSWR from "swr";
import { Main, Box } from "@figuro/ui";
import { RickAndMortyAPIResponse } from "@mount-baker/types/rickyAndMorty";

// helper functions
const createPath = (name: string): string => `/staticprops/${name}`.replace(/\s+/g, "-").toLocaleLowerCase();
const fetcher = (path: string) => fetch(`https://rickandmortyapi.com/${path}`).then((res) => res.json());

export default function Client() {
const characters = useSWR<RickAndMortyAPIResponse>("/api/character", fetcher);

return (
<Main>
<Box>
<h2>getStaticProps</h2>
<Suspense fallback={<p>⌛️ Loading...</p>}>
{characters?.data?.results?.map((character) => (
<ul key={character.id}>
<Link href={createPath(character.name)}>
<li>👾 {character.name}</li>
</Link>
</ul>
))}
</Suspense>
</Box>
</Main>
);
}
tip

For now, if you need to fetch data in a Client Component, we recommend using a third-party library such as SWR or React Query.

Resources