0
0
React Nativemobile~7 mins

Animated.Value and Animated.timing in React Native

Choose your learning style9 modes available
Introduction

Animated.Value lets you create smooth changes in your app's visuals. Animated.timing helps you control how these changes happen over time.

When you want a button to smoothly grow bigger when pressed.
When you want a box to fade out slowly.
When you want to move an image from left to right smoothly.
When you want to animate a progress bar filling up.
Syntax
React Native
const animation = new Animated.Value(startValue);

Animated.timing(animation, {
  toValue: endValue,
  duration: timeInMilliseconds,
  useNativeDriver: true,
}).start();

Animated.Value holds the current value of the animation.

Animated.timing changes the value smoothly from start to end over the given duration.

Examples
This example fades something in by changing opacity from 0 to 1 in half a second.
React Native
const opacity = new Animated.Value(0);

Animated.timing(opacity, {
  toValue: 1,
  duration: 500,
  useNativeDriver: true,
}).start();
This moves something horizontally from 0 to 100 over one second.
React Native
const position = new Animated.Value(0);

Animated.timing(position, {
  toValue: 100,
  duration: 1000,
  useNativeDriver: true,
}).start();
Sample App

This app shows a blue box that starts invisible. When you press the "Fade In" button, the box smoothly appears over one second using Animated.Value and Animated.timing.

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

export default function FadeInBox() {
  const opacity = useRef(new Animated.Value(0)).current;

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

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.box, { opacity }]} />
      <Button title="Fade In" onPress={fadeIn} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    marginBottom: 20,
  },
});
OutputSuccess
Important Notes

Always set useNativeDriver: true for better performance when animating properties like opacity or position.

You can stop an animation anytime by calling .stop() on the animation object.

Animated.Value can hold numbers only, so use it for numeric properties like opacity, position, scale.

Summary

Animated.Value holds the current animation number.

Animated.timing changes that number smoothly over time.

Use these to create smooth, natural animations in your React Native app.