@@ -3,29 +3,52 @@ import { useEffect } from 'react';
33import useRafState from './useRafState' ;
44import { isBrowser , off , on } from './misc/util' ;
55
6- const useWindowSize = ( initialWidth = Infinity , initialHeight = Infinity ) => {
6+ // Define the type for options that can be passed to the hook
7+ interface Options {
8+ initialWidth ?: number ; // Initial width of the window (Default value is Infinity)
9+ initialHeight ?: number ; // Initial height of the window (Default value is Infinity)
10+ onChange ?: ( width : number , height : number ) => void ; // Callback function to execute on window resize (optional)
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)
719 const [ state , setState ] = useRafState < { width : number ; height : number } > ( {
820 width : isBrowser ? window . innerWidth : initialWidth ,
921 height : isBrowser ? window . innerHeight : initialHeight ,
1022 } ) ;
1123
1224 useEffect ( ( ) : ( ( ) => void ) | void => {
25+ // Only run the effect on the browser (to avoid issues with SSR)
1326 if ( isBrowser ) {
1427 const handler = ( ) => {
28+ const width = window . innerWidth ;
29+ const height = window . innerHeight ;
30+
31+ // Update the state with the new window size
1532 setState ( {
16- width : window . innerWidth ,
17- height : window . innerHeight ,
33+ width,
34+ height,
1835 } ) ;
36+
37+ // If an onChange callback is provided, call it with the new dimensions
38+ if ( onChange ) onChange ( width , height ) ;
1939 } ;
2040
41+ // Add event listener for the resize event
2142 on ( window , 'resize' , handler ) ;
2243
44+ // Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization)
2345 return ( ) => {
2446 off ( window , 'resize' , handler ) ;
2547 } ;
2648 }
2749 } , [ ] ) ;
2850
51+ // Return the current window size (width and height)
2952 return state ;
3053} ;
3154
0 commit comments