Skip to content

Instantly share code, notes, and snippets.

@pytqqq
Created February 9, 2023 14:21
import React, { useState, useRef } from "react";
import {
Text,
View,
StyleSheet,
Button,
Animated,
InteractionManager,
Platform,
} from "react-native";
import Constants from "expo-constants";
const ExpensiveTaskStates = {
notStared: "not started",
scheduled: "scheduled",
done: "done",
};
const App = () => {
const animationValue = useRef(new Animated.Value(100));
const [animationState, setAnimationState] = useState(false);
const [expensiveTaskState, setExpensiveTaskState] = useState(
ExpensiveTaskStates.notStared
);
const startAnimationAndScheduleExpensiveTask = () => {
Animated.timing(animationValue.current, {
duration: 2000,
toValue: animationState ? 100 : 300,
useNativeDriver: false,
}).start(() => {
setAnimationState((prev) => !prev);
});
setExpensiveTaskState(ExpensiveTaskStates.scheduled);
InteractionManager.runAfterInteractions(() => {
setExpensiveTaskState(ExpensiveTaskStates.done);
});
};
return (
<View style={styles.container}>
{Platform.OS === "web" ? (
<Text style={styles.infoLabel}>
❗InteractionManager works only on native platforms. Open example on
iOS or Android❗
</Text>
) : (
<>
<Button
title="Start animation and schedule expensive task"
onPress={startAnimationAndScheduleExpensiveTask}
/>
<Animated.View
style={[styles.box, { width: animationValue.current }]}
>
<Text>Animated box</Text>
</Animated.View>
<Text style={styles.paragraph}>
Expensive task status: {expensiveTaskState}
</Text>
</>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
paddingTop: Constants.statusBarHeight,
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: "center",
},
box: {
backgroundColor: "coral",
marginVertical: 20,
height: 50,
},
infoLabel: {
textAlign: "center",
},
});
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment