| 11 | } |
| 12 | |
| 13 | const useWindowSize = ({ |
| 14 | initialWidth = Infinity, |
| 15 | initialHeight = Infinity, |
| 16 | onChange, |
| 17 | }: Options = {}) => { |
| 18 | // Use the useRafState hook to maintain the current window size (width and height) |
| 19 | const [state, setState] = useRafState<{ width: number; height: number }>({ |
| 20 | width: isBrowser ? window.innerWidth : initialWidth, |
| 21 | height: isBrowser ? window.innerHeight : initialHeight, |
| 22 | }); |
| 23 | |
| 24 | useEffect((): (() => void) | void => { |
| 25 | // Only run the effect on the browser (to avoid issues with SSR) |
| 26 | if (isBrowser) { |
| 27 | const handler = () => { |
| 28 | const width = window.innerWidth; |
| 29 | const height = window.innerHeight; |
| 30 | |
| 31 | // Update the state with the new window size |
| 32 | setState({ |
| 33 | width, |
| 34 | height, |
| 35 | }); |
| 36 | |
| 37 | // If an onChange callback is provided, call it with the new dimensions |
| 38 | if (onChange) onChange(width, height); |
| 39 | }; |
| 40 | |
| 41 | // Add event listener for the resize event |
| 42 | on(window, 'resize', handler); |
| 43 | |
| 44 | // Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization) |
| 45 | return () => { |
| 46 | off(window, 'resize', handler); |
| 47 | }; |
| 48 | } |
| 49 | }, []); |
| 50 | |
| 51 | // Return the current window size (width and height) |
| 52 | return state; |
| 53 | }; |
| 54 | |
| 55 | export default useWindowSize; |