1const Component = () => {
2 const { height, width } = useWindowDimensions();
3
4 return (
5 <div>
6 width: {width} ~ height: {height}
7 </div>
8 );
9}
10
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}
1class Main extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = { windowWidth: window.innerWidth };
5 }
6
7 const handleResize = (e) => {
8 this.setState({ windowWidth: window.innerWidth });
9 };
10
11 componentDidMount() {
12 window.addEventListener("resize", this.handleResize);
13 }
14
15 componentWillUnMount() {
16 window.addEventListener("resize", this.handleResize);
17 }
18
19 render() {
20 const { windowWidth } = this.state;
21 return <div>Current window width: {windowWidth}</div>
22 }
23}