`// app/api/hello/route.js
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ message: 'Hello, world!' });
}
// components/ClientComponent.js
'use client'; // Use this directive to mark this as a client component
import React, { useEffect, useState } from 'react';
const ClientComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('/api/hello');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
{data ? <p>{data.message}</p> : <p>Loading...</p>}
</div>
);
};
export default ClientComponent;
// app/page.js
import ClientComponent from '../components/ClientComponent';
export default function Home() {
return (
<div>
<h1>Welcome to Next.js 14 with the App Router!</h1>
<ClientComponent />
</div>
);
}`
I checked https://nextjs.org/docs/app/building-your-application/routing/route-handlers but there are 0 examples on how to call a route handler from a client component.
Can someone please share some best practices? Is using useEffect, and calling the route handler from there, the only way in Next.js 14?