I have a question that needs to be answered; when I use React with some server-side framework like NextJS, and RemixJS, there are some cases where I need to check the condition typeof window
variable in the useEffect hook.
As far as I know, the useEffect
hook always runs on the client side after a component is rendered, so why do we need to check the typeof window
? What is this check for?
Here is an example code that I used to describe the question:
const isBrowser = typeof window !== "undefined";
useEffect(() => {
if (!isBrowser) {
return;
}
// do something here
}, [isBrowser]);
CodePudding user response:
Effects only run on the client. They don’t run during server rendering.
According to the React docs.
The hook might run in other non-browser React environments like React Native where this check would make sense.
CodePudding user response:
In pure React code, you don't need that check. In Next.js, however, components get rendered on the server, sent to the browser as "pure HTML", then rehydrated.
The rendering on the server is done with Node.js; therefore, if you try to use a browser-only API in your component body, like FileReader
, you would get the below error:
ReferenceError: FileReader is not defined
This is what this check is for. But in the useEffect
, with Next.js, you don't need the check, as the hook only gets called in the browser, so there wouldn't be any even if you use, for example, document
.
import { useEffect } from "react";
export default function Home() {
const isBrowser = typeof window !== "undefined";
// This check is needed outside of useEffect, to access browser-only APIs.
if (isBrowser) {
const fileReader = new FileReader();
}
useEffect(() => {
// The check is not needed inside useEffect to access browser-only APIs.
const fileReader = new FileReader();
}, []);
return <>Hello World</>;
}