Skip to content

Commit

Permalink
AnimatedComponent [nfc]: Convert to function component.
Browse files Browse the repository at this point in the history
Use `useRef` for `animatedValue` [1] [2].

Greg points out that we should choose `useEffect` over
`useLayoutEffect` [3].

[1] https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
[2] https://reactnative.dev/docs/animated
[3] zulip#4914 (comment)
  • Loading branch information
chrisbobbe committed Jul 26, 2021
1 parent 5235076 commit a8eba23
Showing 1 changed file with 30 additions and 33 deletions.
63 changes: 30 additions & 33 deletions src/animation/AnimatedComponent.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* @flow strict-local */
import React, { PureComponent } from 'react';
import React, { useRef, useCallback, useEffect } from 'react';
import type { Node as React$Node } from 'react';
import { Animated, Easing } from 'react-native';

Expand All @@ -10,44 +10,41 @@ type Props = $ReadOnly<{|
fullValue: number,
children: React$Node,
style?: Style,
visible: boolean,
useNativeDriver: boolean,
delay: number,
visible?: boolean,
useNativeDriver?: boolean,
delay?: number,
|}>;

export default class AnimatedComponent extends PureComponent<Props> {
static defaultProps = {
visible: true,
useNativeDriver: true,
delay: 0,
};

animatedValue = new Animated.Value(0);

animate() {
Animated.timing(this.animatedValue, {
toValue: this.props.visible ? this.props.fullValue : 0,
delay: this.props.delay,
export default function AnimatedComponent(props: Props) {
const {
visible = true,
useNativeDriver = true,
delay = 0,
fullValue,
children,
stylePropertyName,
style,
} = props;

const animatedValue = useRef(new Animated.Value(0));

const animate = useCallback(() => {
Animated.timing(animatedValue.current, {
toValue: visible ? fullValue : 0,
delay,
duration: 300,
useNativeDriver: this.props.useNativeDriver,
useNativeDriver,
easing: Easing.out(Easing.poly(4)),
}).start();
}
}, [delay, fullValue, useNativeDriver, visible]);

componentDidMount() {
this.animate();
}
useEffect(() => {
animate();
});

componentDidUpdate() {
this.animate();
}

render() {
const { children, stylePropertyName, style } = this.props;
const animatedStyle = {
[stylePropertyName]: this.animatedValue,
};
const animatedStyle = {
[stylePropertyName]: animatedValue.current,
};

return <Animated.View style={[animatedStyle, style]}>{children}</Animated.View>;
}
return <Animated.View style={[animatedStyle, style]}>{children}</Animated.View>;
}

0 comments on commit a8eba23

Please sign in to comment.