reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
11.08k stars 7.56k forks source link

tic-tac-toe example doesn't work in Next.js #6110

Closed dan-mcdonald closed 1 year ago

dan-mcdonald commented 1 year ago

Steps to repro:

  1. Run create-next-app per the first recommended option in the installation guide
  2. Copy tic-tac-toe js into app/page.tsx (and sample CSS into app/globals.css)

Expected result: A playable game of Tic Tac Toe

Actual result:

./app/page.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/ubuntu/dev/tic-tac-toe/app/page.tsx:1:1]
 1 | import { useState } from 'react';
   :          ^^^^^^^^
 2 | 
 3 | function Square({ value, onSquareClick }) {
 4 |   return (
   `----

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

(I hope this isn't a dupe. I tried to do my due diligence searching the issues first. This is related to #6079. I'm hoping that you will find this issue to be more actionable in one way or another.)

Applying the suggested fix does get past the issue.

AhmedBaset commented 1 year ago

Next.js components are server components by default, which means they cannot directly use hooks like useState or useEffect. See Server Components.

To resolve that, you need to convert the component into a client component. To do this, you can add the "use client" directive at the beginning of the file. like so:

'use client'

import { useState } from 'react'

export default function Square({ value, onSquareClick }) {
  // Your component code here
}
rickhanlonii commented 1 year ago

Yeah, what @A7med3bdulBaset said.