|
1 | | -import { useEffect, useState } from 'react'; |
| 1 | +import { useLayoutEffect, useState } from 'react'; |
2 | 2 |
|
3 | 3 | export function useIsPortrait(): boolean { |
4 | 4 | const [isPortrait, setIsPortrait] = useState( |
5 | 5 | () => window.innerWidth < window.innerHeight, |
6 | 6 | ); |
7 | 7 |
|
8 | | - useEffect(() => { |
9 | | - let timer: number; |
| 8 | + useLayoutEffect(() => { |
| 9 | + let timer: ReturnType<typeof setTimeout>; |
10 | 10 | const check = () => { |
| 11 | + setIsPortrait(window.innerWidth < window.innerHeight); |
| 12 | + }; |
| 13 | + |
| 14 | + const handleOrientationChange = () => { |
| 15 | + check(); |
11 | 16 | window.clearTimeout(timer); |
12 | | - timer = window.setTimeout(() => { |
13 | | - setIsPortrait(window.innerWidth < window.innerHeight); |
14 | | - }, 300); |
| 17 | + timer = setTimeout(check, 100); |
| 18 | + timer = setTimeout(check, 300); |
15 | 19 | }; |
| 20 | + |
| 21 | + const mql = window.matchMedia('(orientation: portrait)'); |
| 22 | + mql.addEventListener('change', handleOrientationChange); |
16 | 23 | window.addEventListener('resize', check); |
17 | | - window.addEventListener('orientationchange', check); |
| 24 | + window.addEventListener('orientationchange', handleOrientationChange); |
| 25 | + |
18 | 26 | return () => { |
19 | 27 | window.clearTimeout(timer); |
| 28 | + mql.removeEventListener('change', handleOrientationChange); |
20 | 29 | window.removeEventListener('resize', check); |
21 | | - window.removeEventListener('orientationchange', check); |
| 30 | + window.removeEventListener('orientationchange', handleOrientationChange); |
22 | 31 | }; |
23 | 32 | }, []); |
24 | 33 |
|
|
0 commit comments