react get dynamic window sizes

Solutions on MaxInterview for react get dynamic window sizes by the best coders in the world

showing results for - "react get dynamic window sizes"
Pietro
01 Jan 2021
1import { useState, useEffect } from 'react';
2
3function getWindowDimensions() {
4  const { innerWidth: width, innerHeight: height } = window;
5  return {
6    width,
7    height
8  };
9}
10
11export default function useWindowDimensions() {
12  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
13
14  useEffect(() => {
15    function handleResize() {
16      setWindowDimensions(getWindowDimensions());
17    }
18
19    window.addEventListener('resize', handleResize);
20    return () => window.removeEventListener('resize', handleResize);
21  }, []);
22
23  return windowDimensions;
24}
25
26// Adapted answer from https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs
27// Best suited for using in SPA.
28