Skip to content

Instantly share code, notes, and snippets.

@nguyentuan1696
Created January 11, 2022 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nguyentuan1696/1bdb3a814152554264fda546bccc9470 to your computer and use it in GitHub Desktop.
Save nguyentuan1696/1bdb3a814152554264fda546bccc9470 to your computer and use it in GitHub Desktop.
//dev.to/vvo/how-to-solve-window-is-not-defined-errors-in-react-and-next-js-5f97
// https://frontend-digest.com/why-is-window-not-defined-in-nextjs-44daf7b4604e
import { useEffect, useState } from 'react'
import ExecutionEnvironment from './ExecutionEnvironment'
const windowSizes = {
desktop: 'desktop',
mobile: 'mobile',
ssr: 'ssr',
}
const DesktopThresholdWidth = 996
function getWindowSize() {
if (!ExecutionEnvironment.canUseDOM) {
return windowSizes.ssr
}
return window.innerWidth > DesktopThresholdWidth
? windowSizes.desktop
: windowSizes.mobile
}
// Simulate the SSR window size in dev, so that potential hydration FOUC/layout shift problems can be seen in dev too!
const DevSimulateSSR = process.env.NODE_ENV === 'development' && true
function useWindowSize() {
const [windowSize, setWindowSize] = useState(() => {
if (DevSimulateSSR) {
return 'ssr'
}
return getWindowSize()
})
useEffect(() => {
function updateWindowSize() {
setWindowSize(getWindowSize())
}
const timeout = DevSimulateSSR
? window.setTimeout(updateWindowSize, 1000)
: undefined
window.addEventListener('resize', updateWindowSize)
return () => {
window.removeEventListener('resize', updateWindowSize)
clearTimeout(timeout)
}
}, [])
return windowSize
}
export default useWindowSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment