0
0
React Nativemobile~5 mins

React Native Reanimated

Choose your learning style9 modes available
Introduction

React Native Reanimated helps you create smooth and fast animations in your app. It makes animations run better by using the native side of the phone.

When you want to animate a button press with smooth effects.
When you need to create a swipe gesture that moves a card on the screen.
When you want to animate a list item appearing or disappearing.
When you want to build interactive animations that respond to user touch.
When you want animations that don't slow down your app.
Syntax
React Native
import Animated, { useSharedValue, useAnimatedStyle, withTiming } from 'react-native-reanimated';

const progress = useSharedValue(0);

const animatedStyle = useAnimatedStyle(() => {
  return {
    opacity: progress.value,
  };
});

useSharedValue creates a value that can change over time and be used in animations.

useAnimatedStyle returns styles that update automatically when shared values change.

Examples
This example animates the opacity from 0 to 1 smoothly over 300 milliseconds.
React Native
const progress = useSharedValue(0);

const animatedStyle = useAnimatedStyle(() => ({
  opacity: withTiming(progress.value, { duration: 300 }),
}));
This example animates the scale of a component, making it grow or shrink smoothly.
React Native
const scale = useSharedValue(1);

const animatedStyle = useAnimatedStyle(() => ({
  transform: [{ scale: scale.value }],
}));
Sample App

This app shows a blue square that fades in and out when you press the buttons. The opacity changes smoothly thanks to Reanimated.

React Native
import React from 'react';
import { View, Button } from 'react-native';
import Animated, { useSharedValue, useAnimatedStyle, withTiming } from 'react-native-reanimated';

export default function App() {
  const opacity = useSharedValue(0);

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
  }));

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Animated.View style={[{ width: 100, height: 100, backgroundColor: 'blue' }, animatedStyle]} />
      <Button title="Fade In" onPress={() => { opacity.value = withTiming(1, { duration: 500 }); }} />
      <Button title="Fade Out" onPress={() => { opacity.value = withTiming(0, { duration: 500 }); }} />
    </View>
  );
}
OutputSuccess
Important Notes

Always wrap animated styles in useAnimatedStyle to link them to shared values.

Use withTiming for smooth timing-based animations.

Reanimated runs animations on the native thread, so animations stay smooth even if the JavaScript thread is busy.

Summary

React Native Reanimated helps create smooth, native animations.

Use useSharedValue to hold animation values.

Use useAnimatedStyle to apply animated styles that update automatically.