October 22, 2024
Chicago 12, Melborne City, USA
javascript

Why is window not defined in NextJs 14 useEffect?


I’m having a hard time not seeing this simply as a NextJS bug and want to hear what others think.

Let’s assume that "myFunction" is a third party script loaded in at the top level app/layout file. I’ve checked in browser console that indeed it loads in correctly.

If I place window?.myFunction in as a dependency to this useEffect, we get a "window is not defined" error. Why? I understand that NextJS "pre renders" on server side, despite this being a client file. According to that logic, useEffect really should be ignored on the server side in the first place, AND even if it wasn’t ignored, shouldn’t window?. be checking that the object exists in the first place anyways and at the very least not error out?

Further confusion: the "setIsClient" is kind of ridiculous, but I have placed a debugger statement on the conditional inside of the useEffect, and on the 2nd time it fires, when the "isClient" variable is "true", window is still undefined. I would assume that by the time we’re on the client side, and our setIsClient has finished firing, window should be defined by then…

"use client";
import { useEffect, useState } from "react";

export default function MyPage() {
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    // Set the isClient flag to true once the component is mounted
    setIsClient(true);
  }, []);

  useEffect(() => {
    if (isClient && typeof window !== "undefined" && window?.myFunction) {
      window.myFunction(
        "track",
        12345,
      );
    }
  }, [isClient]);

Appreciate any help. Using NextJS 14.2.15



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video