The simple below component is throwing the following error in Next.js's app
directory when I use useState
:
× You're importing a component that needs useState. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
import { useState } from "react";
export default function Card() {
const [state, setState] = useState("");
return <></>;
}
The simple below component is throwing the following error in Next.js's app
directory when I use useState
:
× You're importing a component that needs useState. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
import { useState } from "react";
export default function Card() {
const [state, setState] = useState("");
return <></>;
}
Share
Improve this question
edited 16 hours ago
Youssouf Oumar
asked Dec 30, 2022 at 21:15
Youssouf OumarYoussouf Oumar
45.6k16 gold badges98 silver badges102 bronze badges
4 Answers
Reset to default 231In the new app
directory, by default, Next.js uses Server Components, where the JSX gets compiled to "pure HTML" and sent to the browser. Like any traditional Backend with a templating engine, such as Express with EJS or Laravel with Blade. This is for better performance, as you can read on the doc:
Server Components allow developers to better leverage server infrastructure. For example, large dependencies that previously would impact the JavaScript bundle size on the client can instead remain entirely on the server, leading to improved performance. They make writing a React application feel similar to PHP or Ruby on Rails, but with the power and flexibility of React for templating UI.
And a Server Component shouldn't contain browser-specific things like click handlers or hooks such as useState
. If you need that, you should add "use client"
at the top to tell Next.js to send the JavaScript needed for that component, making it a Client Component:
"use client"; // This is a client component