Sooner, I needed to get the viewport width on a React app and I wanted it real time updated so I decided to make a hook to deal with it.
Here comes the whole code:
import React, { useEffect, useState } from "react"
const useWindowSize = () => {
const [windowWidth, setWidth] = useState(undefined)
const [windowHeight, setHeight] = useState(undefined)
useEffect(() => {
const getSize = () => {
setWidth(window.innerWidth)
setHeight(window.innerHeight)
}
window.addEventListener('resize', getSize)
getSize()
return () => {
window.removeEventListener('resize', getSize)
}
}, [])
return { windowWidth, windowHeight }
}
export default useWindowSize
Some explanations
const [windowWidth, setWidth] = useState(undefined)
const [windowHeight, setHeight] = useState(undefined)
I initialize the states with undefined
that avoid some build errors and allow you to get rid of 👇️
if (typeof window !== 'undefined'){
// make stuff with window object
}
As the component did mount, the getSize()
function set the states with window.innerWidth
and window.innerHeight
We also handle the event 'resize' on the window
object with getSize()
to keep track of the sizes anytime it could be changed.
Usage
This can be used in component as follow :
import React from 'react'
import useWindowSize from "path/to/useWindowSize"
const Header = () => {
const {windowWidth} = useWindowSize()
return (
<header>
{windowWidth < 700 ? (
<MobileMenu/>
) : (
<DesktopMenu/>
)}
</header>
)
}
I would be pleased to read your comments, seeya 👋️
Top comments (2)
Simple and easy to understand. Thank you for sharing 👍
Thank you. I hope it helps.