Skip to content

Instantly share code, notes, and snippets.

@march213
Created October 17, 2020 03:16
Show Gist options
  • Save march213/bb780a7a8a86feb2b11dce8f8a9d0f60 to your computer and use it in GitHub Desktop.
Save march213/bb780a7a8a86feb2b11dce8f8a9d0f60 to your computer and use it in GitHub Desktop.
React native animation using memo
// ...
import Animated, { Easing } from "react-native-reanimated";
import { runTiming, bInterpolate } from "react-native-redash";
import { useMemoOne } from "use-memo-one";
const {
set,
Value,
Clock,
useCode
};
const MyComponent:React.FC<Props> = ({isVisible, action}) => {
// using useMemoOne from use-memo-one
const { animation, clock } = useMemoOne(
() => ({
animation: new Value(isVisible ? 0 : 1),
clock: new Clock()
}),
[isVisible]
);
useCode(
set(
animation,
// runTiming is a helper from react-native-redash
runTiming(clock, animation, {
toValue: selected ? 1 : 0,
duration: 250,
easing: Easing.inOut(Easing.ease)
})
),
[animation]
);
// interpolated value, bInterpolate is a helper from react-native-redash
const transY = bInterpolate(animation, -20, 0);
return (
<TouchableOpacity onPress={action}>
<Animated.View
style={{ transform: [{ translateY: transY }] }}
>
<Text>I slide down or up based on isVisible value</Text>
</Animated.View>
</TouchableOpacity>
);
}
// when isVisible change, the animation is restarted and the animation value get interpolated again in the other direction, from 0 to 1, or 1 to 0 depending on the visibility flag.
// I hope this would help people having difficulty with functional component implementation and reanimated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment