Next.js Discord

Discord Forum

"window is not defined" error on server even though client component

Answered
Mrigal carp posted this in #help-forum
Open in Discord
Avatar
Mrigal carpOP
My component has "use client"; at the top of the file and it uses window.innerHeight in the root of the component function.
I still see the following error in the server console:

error ReferenceError: window is not defined
    at AccessPaperButton (./components/AccessPaperButton/index.tsx:39:20)
  17 |     const [numPages, setNumPages] = useState<number>();
  18 |     const [pageNumber, setPageNumber] = useState<number>(1);
> 19 |     const height = window.innerHeight * 0.9;


Why is this?
Image
Answered by fuma & joulev pray for Schneider
Don’t get confused by the name, Client components are pre-rendered on the server, you should put it into a useEffect to execute client-side only code.
View full answer

10 Replies

Avatar
fuma & joulev pray for Schneider
Don’t get confused by the name, Client components are pre-rendered on the server, you should put it into a useEffect to execute client-side only code.
Answer
Avatar
fuma & joulev pray for Schneider
Server components -> Server only
Client components -> Both
Avatar
Mrigal carpOP
I see
thank you
Avatar
Asian black bear
use client is identical to normal React SSR like in the /pages directory
Avatar
Mrigal carpOP
well I've never used the pages directory, this is my first time using it
I did end up using useEffect already, I just didn't understand why it was necessary
Avatar
The ORM Hopper
Avatar
Asian black bear
Your page is rendered once on the server side using node.js to obtain an initial view of the page which is sent to the client as HTML. Since node.js does not have a window object, you can not use it in the initial render.
the useEffect hook makes client code that only runs on the client, obviating the node doesn't have window problem