1// useWindowDimensions.js
2
3import { useState, useEffect } from 'react';
4
5export default function useWindowDimensions() {
6
7 const hasWindow = typeof window !== 'undefined';
8
9 function getWindowDimensions() {
10 const width = hasWindow ? window.innerWidth : null;
11 const height = hasWindow ? window.innerHeight : null;
12 return {
13 width,
14 height,
15 };
16 }
17
18 const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
19
20 useEffect(() => {
21 if (hasWindow) {
22 function handleResize() {
23 setWindowDimensions(getWindowDimensions());
24 }
25
26 window.addEventListener('resize', handleResize);
27 return () => window.removeEventListener('resize', handleResize);
28 }
29 }, [hasWindow]);
30
31 return windowDimensions;
32}
33
34// yourComponent.js
35
36import useWindowDimensions from './hooks/useWindowDimensions';
37
38const Component = () => {
39 const { height, width } = useWindowDimensions();
40 /* you can also use default values or alias to use only one prop: */
41 // const { height: windowHeight = 480 } useWindowDimensions();
42
43 return (
44 <div>
45 width: {width} ~ height: {height}
46 </div>
47 );
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}