React-Native Animated: How to loop an animation without resetting the animation value after each loop.
I was struggling to figure out a method of looping React Native Animations without resetting the animated value back to its initial value.
For example I made a simple "Sway" animation that would move my component left and right
let animationX = new Animated.Value(0);
const left = (toValue) => Animated.timing(animationX, {toValue: -toValue, duration: 1500})
const right = (toValue) => Animated.timing(animationX, {toValue, duration: 1500})
const startSwayAnimation = () => {
Animated.loop(
Animated.sequence([
left(100),
right(100),
])
).start()
}
The problem was that my animationX variable resets back to 0 after every loop. I couldn't find any useful resources on how to loop an animation without resetting the value, though there are two dead issues on github:
https://github.com/facebook/react-native/issues/18028 https://github.com/facebook/react-native/issues/20560
I was nearly at the point of considering asking on SO, but then I tried creating a recursive function to loop the animation instead and it worked great
In case anyone else is struggling with this, or knows a better solution (perhaps some config for Animated.loop that I am unaware of) I decided to share this on SO.