0

I have this simple counter:

import React, { useState } from "react";

export default function SSRComponent() {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount((previousCount) => previousCount + 1);
  };

  return (
    <div>
      <h1>Server-Side Rendered Component</h1>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}

And then this error occurs when trying to run the server:

./components/Header.tsx
ReactServerComponentsError:

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.

   ,-[/home/dmytro/PhpstormProjects/prod/proudly-ukrainian/components/Header.tsx:1:1]
 1 | import React, { useState } from "react";
   :                 ^^^^^^^^
 2 | 
 3 | export default function SSRComponent() {
 4 |   const [count, setCount] = useState(0);
   `----

Maybe one of these should be marked as a client entry with "use client":
  ./components/Header.tsx
  ./app/layout.tsx

So how to use simple state in SSR components with Next.js?

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • As the error shows, to use `useState` in Next.js you need to add `use client` and therefore not use SSR for this component https://nextjs.org/docs/getting-started/react-essentials#when-to-use-server-and-client-components – OneQ May 19 '23 at 23:15

0 Answers0