mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
5ec382d1be
Summary:
Automatically provides and subscribes to dimension updates - super easy usage:
```
function MyComponent(props: Props) {
const {width, height, scale, fontScale} = useWindowDimensions();
return <Text ...
};
```
Only window for now - it's what people want 99% of the time, so we'll just shovel out a pit of success for them...
There are still cases where `Dimensions` is needed outside of React component render functions, like in GraphQL variables, so we need to keep the existing module.
Reviewed By: zackargyle
Differential Revision: D16525189
fbshipit-source-id: 0a049fb3be8d92888a8a69e3898d337b93422a09
36 lines
1.0 KiB
JavaScript
36 lines
1.0 KiB
JavaScript
/**
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*
|
|
* @format
|
|
* @flow strict-local
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
import Dimensions from './Dimensions';
|
|
import {type DisplayMetrics} from './NativeDeviceInfo';
|
|
import * as React from 'react';
|
|
|
|
export default function useWindowDimensions(): DisplayMetrics {
|
|
const dims = Dimensions.get('window'); // always read the latest value
|
|
const forceUpdate = React.useState()[1];
|
|
const initialDims = React.useState(dims)[0];
|
|
React.useEffect(() => {
|
|
Dimensions.addEventListener('change', forceUpdate);
|
|
|
|
const latestDims = Dimensions.get('window');
|
|
if (latestDims !== initialDims) {
|
|
// We missed an update between calling `get` in render and
|
|
// `addEventListener` in this handler...
|
|
forceUpdate();
|
|
}
|
|
return () => {
|
|
Dimensions.removeEventListener('change', forceUpdate);
|
|
};
|
|
}, [forceUpdate, initialDims]);
|
|
return dims;
|
|
}
|