How to Create Looping Animations in React Native

In the previous blog post about animation, we discussed how to create spring animation in react native, and now, let’s see how to create animations that loop over how many iterations we define.

In order to create looping animations in react native, we should use Animated.loop() method. Wrap your Animations within Animated.loop() and the animations will act as a loop.

Animated.loop(
      Animated.spring(startValue, {
        toValue: endValue,
        friction: 1,
        useNativeDriver: true,
      }),
      {iterations: 1000},
    ).start();

As you see, the Animated.Spring() animation now loops over 1000 iterations. If you don’t define iterations then the default value of iteration is -1 which means infinity.

Following is the full example of react native looping animation.

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

const Loop = () => {
  const startValue = useRef(new Animated.Value(1)).current;
  const endValue = 1.5;

  useEffect(() => {
    Animated.loop(
      Animated.spring(startValue, {
        toValue: endValue,
        friction: 1,
        useNativeDriver: true,
      }),
      {iterations: 1000},
    ).start();
  }, [startValue]);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.square,
          {
            transform: [
              {
                scale: startValue,
              },
            ],
          },
        ]}
      />
    </View>
  );
};

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

export default Loop;

And here’s the output:

react native animation loop

This blog post is a part of react native animation tutorial series. You can get the source code of all the animation examples in this series from this GitHub repository.

Similar Posts

Leave a Reply