score:2

Accepted answer

you are getting the error because in next.js your code is first server side rendered, and on server there are no browser globals like window, document, etc. to fix it, you can do this:

export default function usewindowdimensions() {
    const [windowdimensions, setwindowdimensions] = usestate({width: 0, height: 0}) // <-- don't invoke here

    useeffect(() => {
        function handleresize() {
            setwindowdimensions(getwindowdimensions())
        }

        handleresize() // <-- invoke this on component mount
        window.addeventlistener('resize', handleresize)
        
        return () => { window.removeeventlistener('resize', handleresize) }
    }, [])

    return windowdimensions
}

it will work because useeffect is guaranteed to run on client side only.

also refer: window is not defined in next.js react app and how to detect window size in next.js ssr using react hook? if you wish to create a hook that handles this for you.

score:1

check if window is defined or not:

if (typeof window !== 'undefined') {
  // you now have access to `window`
}

https://nextjs.org/docs/migrating/from-create-react-app#safely-accessing-web-apis


Related Query

More Query from same tag