1 | import { useEffect } from 'react';
|
---|
2 | import useRafState from './useRafState';
|
---|
3 | import { isBrowser, off, on } from './misc/util';
|
---|
4 | var useWindowSize = function (_a) {
|
---|
5 | var _b = _a === void 0 ? {} : _a, _c = _b.initialWidth, initialWidth = _c === void 0 ? Infinity : _c, _d = _b.initialHeight, initialHeight = _d === void 0 ? Infinity : _d, onChange = _b.onChange;
|
---|
6 | // Use the useRafState hook to maintain the current window size (width and height)
|
---|
7 | var _e = useRafState({
|
---|
8 | width: isBrowser ? window.innerWidth : initialWidth,
|
---|
9 | height: isBrowser ? window.innerHeight : initialHeight,
|
---|
10 | }), state = _e[0], setState = _e[1];
|
---|
11 | useEffect(function () {
|
---|
12 | // Only run the effect on the browser (to avoid issues with SSR)
|
---|
13 | if (isBrowser) {
|
---|
14 | var handler_1 = function () {
|
---|
15 | var width = window.innerWidth;
|
---|
16 | var height = window.innerHeight;
|
---|
17 | // Update the state with the new window size
|
---|
18 | setState({
|
---|
19 | width: width,
|
---|
20 | height: height,
|
---|
21 | });
|
---|
22 | // If an onChange callback is provided, call it with the new dimensions
|
---|
23 | if (onChange)
|
---|
24 | onChange(width, height);
|
---|
25 | };
|
---|
26 | // Add event listener for the resize event
|
---|
27 | on(window, 'resize', handler_1);
|
---|
28 | // Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization)
|
---|
29 | return function () {
|
---|
30 | off(window, 'resize', handler_1);
|
---|
31 | };
|
---|
32 | }
|
---|
33 | }, []);
|
---|
34 | // Return the current window size (width and height)
|
---|
35 | return state;
|
---|
36 | };
|
---|
37 | export default useWindowSize;
|
---|