Detect the browser Window Size with Reactjs Hooks
This Hook is useful to get the current size of the browser window
- Use the
useState()
to initialize thewindowSize
State variable to the first call ofgetSize()
. ThegetSize()
method will return an Object containing the window's width and height . - Use the
useEffect()
Hook to set your new State with the help ofsetWindowSize()
and the EventTarget methodaddEventListener()
- Don't forget to remove your listener in the return Statement of the useEffect
- The Empty array at the End of the
Useeffect
Hook ensures that effect is only run on mount and unmount
const getSize = () => {
return {
width: window.innerWidth,
height: window.innerHeight,
};
};
const [windowSize, setWindowSize] = useState(getSize());
useEffect(() => {
const handleResize = () => setWindowSize(getSize());
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
Live Demo

You like our Content? Follow us to stay up-to-date.