Skip to content

Instantly share code, notes, and snippets.

@arnoldc
Last active November 26, 2023 09:59
Show Gist options
  • Save arnoldc/25b07b8b2efa727ef38ba4da857811ed to your computer and use it in GitHub Desktop.
Save arnoldc/25b07b8b2efa727ef38ba4da857811ed to your computer and use it in GitHub Desktop.
[React Native] react-native-reanimated tips
// Using => useSharedValue + useAnimatedStyle + withTiming
// this is a shared value that be used between UI and JS thread
// example (example is like an accordion)
export default function ExpandingTextBox() {
// creating shared value via useSharedValue
const boxHeight = useSharedValue(150);
// creating worklet via useAnimatedStyle, and incorporating the withTiming method
const boxAnimation = useAnimatedStyle(() => {
return {
height: withTiming(boxHeight.value, {duration: 750})
}
});
// function that toggles the value of boxHeight so it can expand and contract
function toggleHeight() {
boxHeight.value === 450 ? boxHeight.value = 150 : boxHeight.value = 450;
};
// styles to use on our grey box
const styles = {
box: {
width: 400,
height: 150,
backgroundColor: 'grey',
borderRadius: 15,
margin: 100,
padding: 20,
display: 'flex'
}
};
return (
<View style={styles.app}>
{/* Animated.View component, with the typical styles contained in styles.box,
and the worklet "boxHeight" that updates the height property alongside it */}
<Animated.View style={[styles.box, boxAnimation]}>
{/* button that fires off toggleHeight() function every time it's pressed */}
<Button title='More' onPress={() => toggleHeight()} />
</Animated.View>
</View>
)
};
// Terminologies
/*
UI Thread:
- This is the main thread where native UI updates happen.
- For example, if you're animating a view, the animation runs here.
This thread is responsible for drawing things on the screen and responding to user interactions.
It's crucial that this thread remains unblocked to ensure a smooth and responsive user interface.
JS Thread:
- This is where your JavaScript code runs.
React Native operates by running JavaScript code in a separate thread and then updating the native UI through a bridge.
When you interact with a component in your app, the JS thread sends a message across this bridge to the UI thread to update the component.
Great explanation of the JS Thread and UI Thread:
https://aditya01.hashnode.dev/trying-to-understand-the-internals-of-reanimated-2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment