Search code examples
next.jsvercel

Getting Attempted to call the default export from the server but it's on the client on vercel


i am getting this error :

Error: Attempted to call the default export of /vercel/path0/src/hooks/use-window.tsx from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.

while navigating to the pages for example "mydomain.com/login"

here is my use-window.tsx file :

"use client"

import { useState, useEffect } from "react";

type WindowSize = {
    width: number | undefined;
    height: number | undefined;
};

type WindowDimensions = {
    windowSize: WindowSize;
    isMobile: boolean;
    isDesktop: boolean;
};

export default function useWindow(): WindowDimensions {
    const [windowSize, setWindowSize] = useState<WindowSize>({
        width: undefined,
        height: undefined,
    });

    useEffect(() => {
        const handleResize = () => {
            setWindowSize({
                width: window.innerWidth,
                height: window.innerHeight,
            });
        };

        window.addEventListener("resize", handleResize);
        handleResize();

        return () => window.removeEventListener("resize", handleResize);
    }, []);

    const isMobile: boolean = typeof windowSize.width === "number" && windowSize.width < 768;
    const isDesktop: boolean = typeof windowSize.width === "number" && windowSize.width >= 768;

    return { windowSize, isMobile, isDesktop };
}

help me what i am doing wrong.


Solution

  • I don't think "use client" works in hook. You should call your hook useWindow in a client component ie. a component which as "use client".

    Something like below would work:

    "use client"
    
    export default function Component() {
      useWindow()
    }