@@ -3,44 +3,52 @@ import { useEffect } from 'react';
33import useRafState from './useRafState' ;
44import { isBrowser , off , on } from './misc/util' ;
55
6+ // Define the type for options that can be passed to the hook
67interface Options {
7- initialWidth ?: number ;
8- initialHeight ?: number ;
9- onChange ?: ( width : number , height : number ) => void ;
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)
1011}
1112
1213const useWindowSize = ( {
1314 initialWidth = Infinity ,
1415 initialHeight = Infinity ,
1516 onChange,
1617} : Options = { } ) => {
18+ // Use the useRafState hook to maintain the current window size (width and height)
1719 const [ state , setState ] = useRafState < { width : number ; height : number } > ( {
1820 width : isBrowser ? window . innerWidth : initialWidth ,
1921 height : isBrowser ? window . innerHeight : initialHeight ,
2022 } ) ;
2123
2224 useEffect ( ( ) : ( ( ) => void ) | void => {
25+ // Only run the effect on the browser (to avoid issues with SSR)
2326 if ( isBrowser ) {
2427 const handler = ( ) => {
2528 const width = window . innerWidth ;
2629 const height = window . innerHeight ;
2730
31+ // Update the state with the new window size
2832 setState ( {
29- width : window . innerWidth ,
30- height : window . innerHeight ,
33+ width,
34+ height,
3135 } ) ;
3236
37+ // If an onChange callback is provided, call it with the new dimensions
3338 if ( onChange ) onChange ( width , height ) ;
3439 } ;
3540
41+ // Add event listener for the resize event
3642 on ( window , 'resize' , handler ) ;
3743
44+ // Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization)
3845 return ( ) => {
3946 off ( window , 'resize' , handler ) ;
4047 } ;
4148 }
4249 } , [ ] ) ;
4350
51+ // Return the current window size (width and height)
4452 return state ;
4553} ;
4654
0 commit comments