Files
react-native/Libraries/Utilities/useWindowDimensions.js
T
Bruno Lemos 742a544b73 Fix forceUpdate method on useWindowDimensions (#25990)
Summary:
useState won't trigger re-renders if the value passed is the same.

## Changelog

[Internal] [Fixed] - Fix forceUpdate method on useWindowDimensions
Pull Request resolved: https://github.com/facebook/react-native/pull/25990

Test Plan: Codesandbox: https://codesandbox.io/embed/elegant-cori-0ixbx

Differential Revision: D16723962

Pulled By: sahrens

fbshipit-source-id: 8a46152908a90553151e0353bbfd8c2e64cfd2af
2019-08-08 17:12:26 -07:00

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(false)[1].bind(null, v => !v);
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;
}