Skip to content

Commit 3b3c95b

Browse files
dulmandakhfacebook-github-bot
authored andcommitted
Fix useWindowDimensions firing continuously after dims change (#26008)
Summary: #25990 fixed the `forceUpdate` method to actually update the component, but caused the useEffect to fire on every render, causing continuous updates after dimensions changed (e.g. from rotation). This reworks things a bit to be a bit simpler and more idiomatic so it's not quite as confusing, and fixes the bugs. ## Changelog [General] [Fixed] - Fix useWindowDimensions hook firing continuously after dimensions change Pull Request resolved: #26008 Test Plan: Aparently the Mobile Home app supports rotation on iOS now, so replaced it's content with the first `DimensionsExample` and confirmed with logging that `useEffect` fires exactly once, on initial mount, but the view still updates as expected when rotated: https://pxl.cl/Hfds Reviewed By: yungsters Differential Revision: D16765269 Pulled By: sahrens fbshipit-source-id: ef55d8a470dcfe87aa125d4c426bf01cfe0091a7
1 parent f8a64f9 commit 3b3c95b

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

Libraries/Utilities/useWindowDimensions.js

+12-14
Original file line numberDiff line numberDiff line change
@@ -12,24 +12,22 @@
1212

1313
import Dimensions from './Dimensions';
1414
import {type DisplayMetrics} from './NativeDeviceInfo';
15-
import * as React from 'react';
15+
import {useEffect, useState} from 'react';
1616

1717
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);
2922
}
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'));
3028
return () => {
31-
Dimensions.removeEventListener('change', forceUpdate);
29+
Dimensions.removeEventListener('change', handleChange);
3230
};
33-
}, [forceUpdate, initialDims]);
31+
}, []);
3432
return dims;
3533
}

0 commit comments

Comments
 (0)