Skip to content

Commit 745e262

Browse files
Marcoo09facebook-github-bot
authored andcommitted
refactor(rn tester app): change dimensions example to hooks (facebook#35084)
Summary: This pull request migrates the dimensions example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate Dimensions to hooks Pull Request resolved: facebook#35084 Test Plan: The animation works exactly as it did as when it was a class component Reviewed By: yungsters Differential Revision: D40779014 Pulled By: NickGerleman fbshipit-source-id: e740684d3022a945da5abc33b2e8834c6cfabb97
1 parent 07bd590 commit 745e262

File tree

1 file changed

+11
-25
lines changed

1 file changed

+11
-25
lines changed

packages/rn-tester/js/examples/Dimensions/DimensionsExample.js

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,38 +8,24 @@
88
* @flow
99
*/
1010

11-
import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter';
1211
import {Dimensions, Text, useWindowDimensions} from 'react-native';
1312
import * as React from 'react';
13+
import {useState, useEffect} from 'react';
1414

15-
class DimensionsSubscription extends React.Component<
16-
{dim: string, ...},
17-
{dims: Object, ...},
18-
> {
19-
state: {dims: any, ...} = {
20-
dims: Dimensions.get(this.props.dim),
21-
};
15+
type Props = {dim: string};
2216

23-
_dimensionsSubscription: ?EventSubscription;
17+
function DimensionsSubscription(props: Props) {
18+
const [dims, setDims] = useState(() => Dimensions.get(props.dim));
2419

25-
componentDidMount() {
26-
this._dimensionsSubscription = Dimensions.addEventListener(
27-
'change',
28-
dimensions => {
29-
this.setState({
30-
dims: dimensions[this.props.dim],
31-
});
32-
},
33-
);
34-
}
20+
useEffect(() => {
21+
const subscription = Dimensions.addEventListener('change', dimensions => {
22+
setDims(dimensions[props.dim]);
23+
});
3524

36-
componentWillUnmount() {
37-
this._dimensionsSubscription?.remove();
38-
}
25+
return () => subscription.remove();
26+
}, [props.dim]);
3927

40-
render(): React.Node {
41-
return <Text>{JSON.stringify(this.state.dims, null, 2)}</Text>;
42-
}
28+
return <Text>{JSON.stringify(dims, null, 2)}</Text>;
4329
}
4430

4531
const DimensionsViaHook = () => {

0 commit comments

Comments
 (0)