From 745e26288c656237b0f86f6cfc55643eeb0817ca Mon Sep 17 00:00:00 2001 From: Marco Fiorito Date: Mon, 31 Oct 2022 16:23:54 -0700 Subject: [PATCH] refactor(rn tester app): change dimensions example to hooks (#35084) Summary: This pull request migrates the dimensions example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate Dimensions to hooks Pull Request resolved: https://github.com/facebook/react-native/pull/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 --- .../examples/Dimensions/DimensionsExample.js | 36 ++++++------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js b/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js index 008ae41cc9c..8e8d1a28da4 100644 --- a/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js +++ b/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js @@ -8,38 +8,24 @@ * @flow */ -import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter'; import {Dimensions, Text, useWindowDimensions} from 'react-native'; import * as React from 'react'; +import {useState, useEffect} from 'react'; -class DimensionsSubscription extends React.Component< - {dim: string, ...}, - {dims: Object, ...}, -> { - state: {dims: any, ...} = { - dims: Dimensions.get(this.props.dim), - }; +type Props = {dim: string}; - _dimensionsSubscription: ?EventSubscription; +function DimensionsSubscription(props: Props) { + const [dims, setDims] = useState(() => Dimensions.get(props.dim)); - componentDidMount() { - this._dimensionsSubscription = Dimensions.addEventListener( - 'change', - dimensions => { - this.setState({ - dims: dimensions[this.props.dim], - }); - }, - ); - } + useEffect(() => { + const subscription = Dimensions.addEventListener('change', dimensions => { + setDims(dimensions[props.dim]); + }); - componentWillUnmount() { - this._dimensionsSubscription?.remove(); - } + return () => subscription.remove(); + }, [props.dim]); - render(): React.Node { - return {JSON.stringify(this.state.dims, null, 2)}; - } + return {JSON.stringify(dims, null, 2)}; } const DimensionsViaHook = () => {