"window" is not defined when rendering client component
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
Even though this component is marked with "use client", I get an error when trying to log the
The error:
It does get successfully logged to the console, but this error still shows up. Why?
window
object."use client";
export default function App() {
console.log(window);
return <div>my app</div>;
}
The error:
⨯ ReferenceError: window is not defined
at window (app\page.tsx:4:16)
2 |
3 | export default function App() {
> 4 | console.log(window);
| ^
5 |
6 | return <div>my app</div>;
7 | } {
digest: '1400661120'
}
It does get successfully logged to the console, but this error still shows up. Why?
Answered by B33fb0n3
when you add 'use client' on top, it will be still rendered on the serverside (SSR) and only hydrated on the client. On server there is no window and like that the error is thrown. Either remove the function, add it to a use effect or skip SSR loading (maybe there are other options as well. We come back to them when needed)
2 Replies
@Transvaal lion Even though this component is marked with "use client", I get an error when trying to log the `window` object.
jsx
"use client";
export default function App() {
console.log(window);
return <div>my app</div>;
}
The error:
jsx
⨯ ReferenceError: window is not defined
at window (app\page.tsx:4:16)
2 |
3 | export default function App() {
> 4 | console.log(window);
| ^
5 |
6 | return <div>my app</div>;
7 | } {
digest: '1400661120'
}
It does get successfully logged to the console, but this error still shows up. Why?
when you add 'use client' on top, it will be still rendered on the serverside (SSR) and only hydrated on the client. On server there is no window and like that the error is thrown. Either remove the function, add it to a use effect or skip SSR loading (maybe there are other options as well. We come back to them when needed)
Answer