|
12 | 12 |
|
13 | 13 | import Dimensions from './Dimensions';
|
14 | 14 | import {type DisplayMetrics} from './NativeDeviceInfo';
|
15 |
| -import * as React from 'react'; |
| 15 | +import {useEffect, useState} from 'react'; |
16 | 16 |
|
17 | 17 | export default function useWindowDimensions(): DisplayMetrics {
|
18 |
| - const dims = Dimensions.get('window'); // always read the latest value |
19 |
| - const forceUpdate = React.useState(false)[1].bind(null, v => !v); |
20 |
| - const initialDims = React.useState(dims)[0]; |
21 |
| - React.useEffect(() => { |
22 |
| - Dimensions.addEventListener('change', forceUpdate); |
23 |
| - |
24 |
| - const latestDims = Dimensions.get('window'); |
25 |
| - if (latestDims !== initialDims) { |
26 |
| - // We missed an update between calling `get` in render and |
27 |
| - // `addEventListener` in this handler... |
28 |
| - forceUpdate(); |
| 18 | + const [dims, setDims] = useState(() => Dimensions.get('window')); |
| 19 | + useEffect(() => { |
| 20 | + function handleChange({window}) { |
| 21 | + setDims(window); |
29 | 22 | }
|
| 23 | + Dimensions.addEventListener('change', handleChange); |
| 24 | + // We might have missed an update between calling `get` in render and |
| 25 | + // `addEventListener` in this handler, so we set it here. If there was |
| 26 | + // no change, React will filter out this update as a no-op. |
| 27 | + setDims(Dimensions.get('window')); |
30 | 28 | return () => {
|
31 |
| - Dimensions.removeEventListener('change', forceUpdate); |
| 29 | + Dimensions.removeEventListener('change', handleChange); |
32 | 30 | };
|
33 |
| - }, [forceUpdate, initialDims]); |
| 31 | + }, []); |
34 | 32 | return dims;
|
35 | 33 | }
|
0 commit comments