Skip to content

Commit c868d5b

Browse files
Marcoo09facebook-github-bot
authored andcommitted
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: #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
1 parent b655e69 commit c868d5b

File tree

1 file changed

+23
-34
lines changed

1 file changed

+23
-34
lines changed

packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -10,46 +10,35 @@
1010

1111
import type {Node} from 'React';
1212
import {ActivityIndicator, StyleSheet, View} from 'react-native';
13-
import React, {Component} from 'react';
13+
import React, {useState, useCallback, useRef, useEffect} from 'react';
1414

15-
type State = {|animating: boolean|};
16-
type Props = $ReadOnly<{||}>;
17-
type Timer = TimeoutID;
15+
function ToggleAnimatingActivityIndicator() {
16+
const timer = useRef();
1817

19-
class ToggleAnimatingActivityIndicator extends Component<Props, State> {
20-
_timer: Timer;
18+
const [animating, setAnimating] = useState(true);
2119

22-
constructor(props: Props) {
23-
super(props);
24-
this.state = {
25-
animating: true,
26-
};
27-
}
28-
29-
componentDidMount() {
30-
this.setToggleTimeout();
31-
}
20+
const setToggleTimeout = useCallback(() => {
21+
timer.current = setTimeout(() => {
22+
setAnimating(currentState => !currentState);
23+
setToggleTimeout();
24+
}, 2000);
25+
}, []);
3226

33-
componentWillUnmount() {
34-
clearTimeout(this._timer);
35-
}
27+
useEffect(() => {
28+
setToggleTimeout();
3629

37-
setToggleTimeout() {
38-
this._timer = setTimeout(() => {
39-
this.setState({animating: !this.state.animating});
40-
this.setToggleTimeout();
41-
}, 2000);
42-
}
30+
return () => {
31+
clearTimeout(timer.current);
32+
};
33+
}, [timer, setToggleTimeout]);
4334

44-
render(): Node {
45-
return (
46-
<ActivityIndicator
47-
animating={this.state.animating}
48-
style={[styles.centering, {height: 80}]}
49-
size="large"
50-
/>
51-
);
52-
}
35+
return (
36+
<ActivityIndicator
37+
animating={animating}
38+
style={[styles.centering, {height: 80}]}
39+
size="large"
40+
/>
41+
);
5342
}
5443

5544
const styles = StyleSheet.create({

0 commit comments

Comments
 (0)