最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - You're importing a component that needs useState. It only works in a Client Component, but none of its pare

programmeradmin8浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 231

In 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 
发布评论

评论列表(0)

  1. 暂无评论