How to Create Delays in between Animations in React Native

In the previous blog post, we went through how the multiple animations are managed using methods such as parallel() and sequence(). Now, let’s discuss how to add delays in between animations in react native.

When you are composing animations with sequence() and stagger() you can use Animated.delay() method to begin animations after a delay. Let’s see how to use the delay() method.

Animated.sequence([
      Animated.timing(initialMove, {
        toValue: endMove,
        duration: duration,
        useNativeDriver: true,
      }),
      Animated.delay(1000),
      Animated.timing(initialOpacity, {
        toValue: endOpacity,
        duration: duration,
        useNativeDriver: true,
      }),
    ]).start();

Here, there’s a delay of 1000 ms between two animations. You should place the delay appropriately matching your needs.

Here’s the full example of creating delays in react native animation.

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

const Delay = () => {
  const initialOpacity = useRef(new Animated.Value(1)).current;
  const initialMove = useRef(new Animated.Value(0)).current;
  const endOpacity = 0;
  const endMove = 100;
  const duration = 3000;

  useEffect(() => {
    Animated.sequence([
      Animated.timing(initialMove, {
        toValue: endMove,
        duration: duration,
        useNativeDriver: true,
      }),
      Animated.delay(1000),
      Animated.timing(initialOpacity, {
        toValue: endOpacity,
        duration: duration,
        useNativeDriver: true,
      }),
    ]).start();
  }, [initialMove, initialOpacity]);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.square,
          {
            opacity: initialOpacity,
            translateX: initialMove,
          },
        ]}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
  },
  square: {
    height: 150,
    width: 150,
    backgroundColor: 'red',
  },
});

export default Delay;

Here’s the output of the delayed animation example:

react native delay animation example

You can get the source code of all my animation examples given in this tutorial series from this Github repository.

Similar Posts

Leave a Reply