"window is not defined" error on server even though client component
Answered
Mrigal carp posted this in #help-forum
Mrigal carpOP
My component has
I still see the following error in the server console:
Why is this?
"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?
Answered by fuma 💙 joulev
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.10 Replies
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
Server components -> Server only
Client components -> Both
Client components -> Both
Mrigal carpOP
I see
thank you
Asian black bear
use client
is identical to normal React SSR like in the /pages
directoryMrigal 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
[Read More Here](https://nextjs-faq.com/browser-api-client-component)
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