useWindowDimensions.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow strict-local
  9. */
  10. 'use strict';
  11. import Dimensions from './Dimensions';
  12. import {type DisplayMetrics} from './NativeDeviceInfo';
  13. import {useEffect, useState} from 'react';
  14. export default function useWindowDimensions(): DisplayMetrics {
  15. const [dimensions, setDimensions] = useState(() => Dimensions.get('window'));
  16. useEffect(() => {
  17. function handleChange({window}) {
  18. if (
  19. dimensions.width !== window.width ||
  20. dimensions.height !== window.height ||
  21. dimensions.scale !== window.scale ||
  22. dimensions.fontScale !== window.fontScale
  23. ) {
  24. setDimensions(window);
  25. }
  26. }
  27. Dimensions.addEventListener('change', handleChange);
  28. // We might have missed an update between calling `get` in render and
  29. // `addEventListener` in this handler, so we set it here. If there was
  30. // no change, React will filter out this update as a no-op.
  31. handleChange({window: Dimensions.get('window')});
  32. return () => {
  33. Dimensions.removeEventListener('change', handleChange);
  34. };
  35. }, [dimensions]);
  36. return dimensions;
  37. }