|
1 |
| -export { useWindowDimensions } from "react-native"; |
| 1 | +import { useEffect, useState } from "react"; |
| 2 | +import { Dimensions } from "react-native"; |
| 3 | + |
| 4 | +import type { WindowDimensionsEventData } from "../../types"; |
| 5 | + |
| 6 | +const screen = Dimensions.get("screen"); |
| 7 | + |
| 8 | +let initialDimensions: WindowDimensionsEventData = { |
| 9 | + width: screen.width, |
| 10 | + height: screen.height, |
| 11 | +}; |
| 12 | + |
| 13 | +Dimensions.addEventListener("change", (e) => { |
| 14 | + initialDimensions = { |
| 15 | + width: e.screen.width, |
| 16 | + height: e.screen.height, |
| 17 | + }; |
| 18 | +}); |
| 19 | + |
| 20 | +/** |
| 21 | + * On iOS we need to use `screen`, because this property is derived from `mainScreen.bounds.size` |
| 22 | + * while `window` is based on `[RCTKeyWindowValuesProxy sharedInstance].windowSize`, which can have |
| 23 | + * out of date values (especially when device gets rotated). |
| 24 | + * |
| 25 | + * @returns Window dimension. |
| 26 | + * @example |
| 27 | + * ``` |
| 28 | + * const { height, window } = useWindowDimensions(); |
| 29 | + * ``` |
| 30 | + */ |
| 31 | +export const useWindowDimensions = () => { |
| 32 | + const [dimensions, setDimensions] = useState(initialDimensions); |
| 33 | + |
| 34 | + useEffect(() => { |
| 35 | + const subscription = Dimensions.addEventListener("change", (e) => { |
| 36 | + setDimensions({ |
| 37 | + width: e.screen.width, |
| 38 | + height: e.screen.height, |
| 39 | + }); |
| 40 | + }); |
| 41 | + |
| 42 | + // we might have missed an update between reading a value in render and |
| 43 | + // `addListener` in this handler, so we set it here. If there was |
| 44 | + // no change, React will filter out this update as a no-op. |
| 45 | + setDimensions(initialDimensions); |
| 46 | + |
| 47 | + return () => { |
| 48 | + subscription.remove(); |
| 49 | + }; |
| 50 | + }, []); |
| 51 | + |
| 52 | + return dimensions; |
| 53 | +}; |
0 commit comments