Skip to main content

Implementing Animations with Animated API

1. Using Animated.Value

Property Description Default Value Example
Animated.Value Represents a single numeric value that can be animated 0 new Animated.Value(0)
setValue Sets the value immediately without animation None animatedValue.setValue(100)
setOffset Sets an offset that is added to the value during animation 0 animatedValue.setOffset(50)
flattenOffset Resets the offset to zero and applies it to the value None animatedValue.flattenOffset()

Example: Basic Animation with Animated.Value

import React, { useRef } from 'react';
import { Animated, View } from 'react-native';

const BasicAnimation = () => {
  const animationValue = useRef(new Animated.Value(0)).current;

  const startAnimation = () => {
    Animated.timing(animationValue, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true
    }).start();
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Animated.View
        style={{
          width: 100,
          height: 100,
          backgroundColor: 'blue',
          opacity: animationValue
        }}
      />
    </View>
  );
};

export default BasicAnimation;

2. Creating Timing Animations

Example: Basic timing animation

import Animated, {&#160;timing&#160;} from 'react-native';

const&#160;animatedValue&#160;=&#160;new&#160;Animated.Value(0);

Animated.timing(animatedValue,&#160;{
&#160;&#160;toValue:&#160;1,
&#160;&#160;duration:&#160;1000,
&#160;&#160;useNativeDriver:&#160;true
}).start();
Property Description Default Notes
toValue Final value of the animation 0 Required
duration Duration of the animation in milliseconds 250 Optional
easing Easing function to use easeInOut Optional
delay Delay before starting the animation in milliseconds 0 Optional
useNativeDriver Whether to use native driver for performance false Required for most animations
Note: Always set useNativeDriver to true if possible for better performance.

3. Creating Spring Animations

Property Values Description
bounciness 8 Controls the bounciness of the spring. Higher values create more bouncy animations.
speed 12 Controls the speed of the spring animation. Higher values make it faster.
stiffness 100 Determines how stiff the spring is. Higher values make it less flexible.
damping 10 Controls how quickly the spring comes to rest. Higher values reduce oscillation.
mass 1 Represents the mass of the animated object. Higher values make the animation feel heavier.

Example: Basic Spring Animation

<Animated.View
  style={[
    styles.box,
    {
      transform: [
        {
          translateY: animatedValue
        }
      ]
    }
  ]}
>
</Animated.View>

const animatedValue = new Animated.Value(0);

Animated.spring(animatedValue, {
  toValue: 100,
  useNativeDriver: true,
  bounciness: 8,
  speed: 12
}).start();

Example: Spring with Custom Stiffness

Animated.spring(animatedValue, {
  toValue: 200,
  useNativeDriver: true,
  stiffness: 150,
  damping: 15
}).start();

4. Using Animated.decay

Property Description Default
velocity Initial velocity of the animation (in pixels per second) 0
deceleration Deceleration rate (0.95 = 5% per second) 0.998
clamp Clamp value to a range (e.g., [0, 100]) null

Example: Basic decay animation

import Animated, { decay } from &#x27;react-native&#x27;;

const animatedValue = new Animated.Value(0);
Animated.decay(animatedValue, {
  velocity: 100,
  deceleration: 0.998,
}).start();
Note: Animated.decay is useful for momentum-based animations, such as flinging a scroll view or dragging an element with inertia.

5. Combining Animations

Example: Combining Multiple Animations

import Animated, {&#x00A;  useAnimatedStyle,&#x00A;  withSequence,&#x00A;  withTiming,&#x00A;} from &#x27;react-native-reanimated&#x27;;&#x00A;&#x00A;const AnimatedComponent = () => {&#x00A;  const scale = useAnimatedStyle(() => ({&#x00A;    transform: [{ scale: withSequence(withTiming(1, { duration: 500 }), withTiming(1.2, { duration: 200 }), withTiming(1, { duration: 500 })) }],&#x00A;  }));&#x00A;&#x00A;  return (&#x00A;    <Animated.View style={scale}>&#x00A;      <Text>Scaled and Pulsed</Text>&#x00A;    </Animated.View>&#x00A;  );&#x00A;};
Animation Type Description Usage
withSequence Sequentially plays animations in order withSequence(withTiming(1), withDelay(200, withSpring(1.2)))
withRepeat Repeats an animation a specified number of times withRepeat(withTiming(1), 3)
withDelay Introduces a delay before starting an animation withDelay(500, withTiming(1))
Note: Use withSequence to create complex animation flows by chaining multiple animations together.
Warning: Avoid deeply nested animations as they can impact performance.

6. Implementing Animated Transforms

Property Values Description
transform Array Array of transform operations to apply to the animated component
translateX Animated.Value Translation along the X-axis in pixels
translateY Animated.Value Translation along the Y-axis in pixels
scale Animated.Value Scale factor (1.0 = original size)
scaleX Animated.Value Scale factor along X-axis
scaleY Animated.Value Scale factor along Y-axis
rotate Animated.Value Rotation in radians
rotateX Animated.Value Rotation around X-axis in radians
rotateY Animated.Value Rotation around Y-axis in radians
rotateZ Animated.Value Rotation around Z-axis in radians

Example: Basic Transform Animation

import React, { useRef } from 'react';
import { Animated, View } from 'react-native';

const TransformAnimation = () => {
  const translateX = useRef(new Animated.Value(0)).current;

  Animated.timing(translateX, {
    toValue: 100,
    duration: 500,
    useNativeDriver: true
  }).start();

  return (
    <Animated.View
      style={{
        transform: [{ translateX }]
      }}
    >
      <View style={{ width: 50, height: 50, backgroundColor: 'blue' }} />
    </Animated.View>
  );
};

export default TransformAnimation;

Example: Combined Transform Operations

import React, { useRef } from 'react';
import { Animated, View } from 'react-native';

const CombinedTransform = () => {
  const translateX = useRef(new Animated.Value(0)).current;
  const scaleX = useRef(new Animated.Value(1)).current;

  Animated.parallel([
    Animated.timing(translateX, {
      toValue: 50,
      duration: 500,
      useNativeDriver: true
    }),
    Animated.timing(scaleX, {
      toValue: 1.5,
      duration: 500,
      useNativeDriver: true
    })
  ]).start();

  return (
    <Animated.View
      style={{
        transform: [
          { translateX },
          { scaleX }
        ]
      }}
    >
      <View style={{ width: 50, height: 50, backgroundColor: 'red' }} />
    </Animated.View>
  );
};

export default CombinedTransform;

7. Using useNativeDriver

Property Values Description
useNativeDriver true | false Enables or disables native driver for animations. Defaults to false.

Example: Using useNativeDriver

import Animated, { FadeIn } from 'react-native-reanimated';

const AnimatedComponent = Animated.createAnimatedComponent(View);

<AnimatedComponent
  entering={FadeIn.duration(500).useNativeDriver(true)}
  style={{ opacity: animationValue }}
>
  <Text>Animated Text</Text>
</AnimatedComponent>
Note: useNativeDriver is required for animations to run smoothly on the UI thread. It's only supported for a limited set of animated values.

8. Creating Interpolations

Example: Basic Interpolation

import { Animated } from 'react-native';\n\nconst interpolation = Animated.timing(\n  animatedValue,\n  {\n    toValue: 1,\n    duration: 1000,\n    useNativeDriver: true\n  }\n);\n\nconst outputRange = [0, 1];\nconst inputRange = [0, 1];\n\nconst interpolatedValue = animatedValue.interpolate({\n  inputRange,\n  outputRange\n});
Property Description Values
inputRange Array of numbers that define the input domain [0, 1]
outputRange Array of numbers that define the output domain [0, 1]
extrapolate How to handle values outside the input range 'extend', 'clamp', 'identity'
extrapolateLeft How to handle values below the lowest input value 'extend', 'clamp', 'identity'
extrapolateRight How to handle values above the highest input value 'extend', 'clamp', 'identity'
Note: Interpolations are used to map input values to output values for animations. They can be used with any Animated value.

Example: Advanced Interpolation with Extrapolation

const animatedValue = new Animated.Value(0);\n\nconst interpolatedValue = animatedValue.interpolate({\n  inputRange: [0, 1],\n  outputRange: [0, 100],\n  extrapolateLeft: 'clamp',\n  extrapolateRight: 'extend'\n});

9. Handling Animation Loops

Example: Basic Loop with repeat()

import { Animated } from 'react-native';

const loopAnimation = Animated.loop(
  Animated.sequence([
    Animated.timing(scale, {
      toValue: 1.2,
      duration: 500,
      useNativeDriver: true,
    }),
    Animated.timing(scale, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }),
  ])
);

loopAnimation.start();
Method Description Parameters Notes
Animated.loop() Repeats an animation indefinitely or for a specified number of times animation, iterations Use iterations to limit loop count
Animated.sequence() Runs animations in sequence animations Each animation starts after the previous one ends
Animated.parallel() Runs animations in parallel animations All animations start at the same time
Note: Loop animations must be stopped manually using stop() to prevent memory leaks.

Example: Loop with Iteration Limit

const limitedLoop = Animated.loop(
  Animated.sequence([
    Animated.timing(opacity, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true,
    }),
    Animated.timing(opacity, {
      toValue: 1,
      duration: 300,
      useNativeDriver: true,
    }),
  ]),
  3 // Loop 3 times
);

limitedLoop.start();

10. Using LayoutAnimation API

Example: Basic LayoutAnimation

import { LayoutAnimation, Platform, UIManager } from 'react-native';

// Enable LayoutAnimation on Android
if (Platform.OS === 'android') {
  UIManager.setLayoutAnimationEnabledExperimental &&
    UIManager.setLayoutAnimationEnabledExperimental(true);
}

// Trigger layout animation
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);

// Component will animate its layout changes
Property Description Values
LayoutAnimation.Presets Predefined animation presets easeInEaseOut, linear, spring, keyboard
LayoutAnimation.configureNext() Configures the next layout animation Object with duration, create, update, delete
Note: LayoutAnimation only works with View, Text, and Image components.
Warning: LayoutAnimation does not support Animated components or complex nested animations.

Key Features

  • Automatically animates layout changes
  • Works with View, Text, and Image
  • Supports predefined presets

11. Implementing Animated Event Bindings

Example: Basic Animated Event Binding

import React, { useRef } from 'react';
import { Animated, PanGestureHandler, State } from 'react-native';

const AnimatedEventBinding = () => {
  const translateX = useRef(new Animated.Value(0)).current;
  const panGestureEvent = Animated.event(
    [{ nativeEvent: { translationX: translateX } }],
    { useNativeDriver: true }
  );

  return (
    <PanGestureHandler
      onGestureEvent={panGestureEvent}
      onHandlerStateChange={(e) => {
        if (e.nativeEvent.state === State.END) {
          translateX.setValue(0);
        }
      }}
    >
      <Animated.View
        style={{
          transform: [{ translateX }],
        }}
      >
        <View style={{ width: 100, height: 100, backgroundColor: 'blue' }} />
      </Animated.View>
    </PanGestureHandler>
  );
};

export default AnimatedEventBinding;
Property Description Usage
Animated.event Creates an event handler for animated values Animated.event([config], options)
nativeEvent Maps gesture event properties to animated values { translationX: translateX }
useNativeDriver Enables native driver for performance { useNativeDriver: true }
Note: The Animated.event function is used to bind gesture events to animated values. It requires a configuration array and optional options object.
Warning: Always ensure that useNativeDriver is set to true for better performance, but it's only supported for certain properties like transform and opacity.

12. Creating Custom Animated Components

Example: Custom Animated Text Component

import React, { useRef } from 'react';
import { Animated, Text, View } from 'react-native';

const AnimatedText = () => {
  const opacity = useRef(new Animated.Value(0)).current;

  React.useEffect(() => {
    Animated.timing(opacity, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true
    }).start();
  }, []);

  return (
    <Animated.Text style={{ opacity }}>
      Animated Text Component
    </Animated.Text>
  );
};

export default AnimatedText;
Property Description Default
animatedValue Instance of Animated.Value or Animated.ValueXY undefined
useNativeDriver Boolean indicating if animation should run on native thread false
Note: Native driver is recommended for better performance.
Warning: Custom animated components must be wrapped in Animated.View or similar.

Was this article helpful?