/
index.js
43 lines (38 loc) · 935 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* WordPress dependencies
*
* @ignore
*/
import { useEffect, useState } from '@wordpress/element';
/**
* Get the current size of the browser window.
*
* @function
* @since 1.3.0
* @name useWindowSize
* @return {Object} An object containing the window's width and height.
* @example
*
* const size = useWindowSize();
*/
export default () => {
// Initialize state with undefined width/height so server and client renders match.
const [ size, setSize ] = useState( {
width: undefined,
height: undefined,
} );
useEffect( () => {
// Handler to call on window resize
const handleResize = () => {
// Set window width/height to state
setSize( {
width: window.innerWidth,
height: window.innerHeight,
} );
};
window.addEventListener( 'resize', handleResize );
handleResize();
return () => window.removeEventListener( 'resize', handleResize );
}, [] );
return size;
};