From c868d5b26c5d680603d3f653de9277124c1b539b Mon Sep 17 00:00:00 2001 From: Marco Fiorito Date: Wed, 26 Oct 2022 03:21:04 -0700 Subject: [PATCH] refactor(rn tester app): change activity indicator to hooks (#35071) Summary: This pull request migrates the activity indicator example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate ActivityIndicator to hooks Pull Request resolved: https://github.com/facebook/react-native/pull/35071 Test Plan: The animation works exactly as it did as when it was a class component Reviewed By: jacdebug Differential Revision: D40698379 Pulled By: NickGerleman fbshipit-source-id: 08b275fcc4e3a10b5872e0031fa2ecce5360a7b9 --- .../ActivityIndicatorExample.js | 57 ++++++++----------- 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js b/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js index 188302df2f78c2..7be8bc4a5dd5f3 100644 --- a/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js +++ b/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js @@ -10,46 +10,35 @@ import type {Node} from 'React'; import {ActivityIndicator, StyleSheet, View} from 'react-native'; -import React, {Component} from 'react'; +import React, {useState, useCallback, useRef, useEffect} from 'react'; -type State = {|animating: boolean|}; -type Props = $ReadOnly<{||}>; -type Timer = TimeoutID; +function ToggleAnimatingActivityIndicator() { + const timer = useRef(); -class ToggleAnimatingActivityIndicator extends Component { - _timer: Timer; + const [animating, setAnimating] = useState(true); - constructor(props: Props) { - super(props); - this.state = { - animating: true, - }; - } - - componentDidMount() { - this.setToggleTimeout(); - } + const setToggleTimeout = useCallback(() => { + timer.current = setTimeout(() => { + setAnimating(currentState => !currentState); + setToggleTimeout(); + }, 2000); + }, []); - componentWillUnmount() { - clearTimeout(this._timer); - } + useEffect(() => { + setToggleTimeout(); - setToggleTimeout() { - this._timer = setTimeout(() => { - this.setState({animating: !this.state.animating}); - this.setToggleTimeout(); - }, 2000); - } + return () => { + clearTimeout(timer.current); + }; + }, [timer, setToggleTimeout]); - render(): Node { - return ( - - ); - } + return ( + + ); } const styles = StyleSheet.create({