I am facing a problem I can't seem to solve.
I have a custom hook that sets the height and width of the window. But since nextjs is SSR I get the error that window is not defined.
My problem lies in putting the hook in a if statement or useeffect hook.
Current code (useWindowDimensions.tsx):
import { useState, useEffect } from 'react'
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window
return {
width,
height,
}
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions())
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions())
}
window.addEventListener('resize', handleResize)
// code here
return () => window.removeEventListener('resize', handleResize)
}, [])
return windowDimensions
}
Current code:
const { height, width } = useWindowDimensions()
const dimensions = () => {
if (width > 1900) return width * 0.4
if (width > 1000) return width * 0.3
if (width > 800) return width * 0.2
if (width < 800) return width * 0.1
}
I can't put getWindowDimensions() in an useEffect because the rules of hooks
useEffect(() => {
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window
return {
width,
height,
}
}
})