File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { useState , useEffect } from "react" ;
2+
3+ interface WindowSize {
4+ width : number ;
5+ height : number ;
6+ isMobile : boolean ;
7+ isTablet : boolean ;
8+ isDesktop : boolean ;
9+ }
10+
11+ /**
12+ * Track window dimensions with responsive breakpoints.
13+ *
14+ * @example
15+ * const { width, isMobile } = useWindowSize();
16+ * if (isMobile) return <MobileLayout />;
17+ */
18+ export function useWindowSize ( ) : WindowSize {
19+ const [ size , setSize ] = useState < WindowSize > ( ( ) => getSize ( ) ) ;
20+
21+ function getSize ( ) : WindowSize {
22+ const width = typeof window !== "undefined" ? window . innerWidth : 1024 ;
23+ const height = typeof window !== "undefined" ? window . innerHeight : 768 ;
24+ return {
25+ width,
26+ height,
27+ isMobile : width < 768 ,
28+ isTablet : width >= 768 && width < 1024 ,
29+ isDesktop : width >= 1024 ,
30+ } ;
31+ }
32+
33+ useEffect ( ( ) => {
34+ let timeout : ReturnType < typeof setTimeout > ;
35+ function handler ( ) {
36+ clearTimeout ( timeout ) ;
37+ timeout = setTimeout ( ( ) => setSize ( getSize ( ) ) , 100 ) ;
38+ }
39+ window . addEventListener ( "resize" , handler ) ;
40+ return ( ) => {
41+ window . removeEventListener ( "resize" , handler ) ;
42+ clearTimeout ( timeout ) ;
43+ } ;
44+ } , [ ] ) ;
45+
46+ return size ;
47+ }
You can’t perform that action at this time.
0 commit comments