I am trying to use a useState
hook with the window
property in Nextjs. However, I am getting the error, ReferenceError: window is not defined
.
The goal: update the size state whenever the screen size changes
Implementation:
import { useState } from 'react'
export const Dashboard = ({ children }) => {
const [size, setSize] = useState(window.innerWidth) // <<< Error thrown here
const updateSize = () => setSize(window.innerWidth)
useEffect(() => (window.onresize = updateSize))
}
return {
<div className=`{$toggleMenu || size >= 768 ? 'flex' : 'hidden'}`}>content</div>
}
I've tried placing the useState
in a conditional and useEffect hook, but this does not fix the issue.