Is Animation in react native a headache…??

Learning React Native Reanimated 2 can be a rewarding experience for building performant and smooth animations in your React Native apps. To get started, follow these steps with a real-world example

// Ensure you have React Native installed on your system.

// Create a new React Native project: 
npx react-native init MyReanimatedApp

// Install React Native Reanimated 2:
npm install react-native-reanimated react-native-gesture-handler

The main concept of Reanimated can be summarized in three key points:

1. Declarative Animations: Reanimated enables you to create animations declaratively using JavaScript functions. Instead of setting up animations with separate styles and state changes, you define animated values and functions that control how those values change over time.

2. Worklet Functions: Reanimated uses special “worklet” functions to perform animations on the native thread rather than the JavaScript thread. This means that animations run with higher performance and smoother frame rates, resulting in a more responsive user interface.

3. Shared Values: Reanimated allows you to share animated values between the native and JavaScript threads. This sharing mechanism ensures that animations are tightly integrated with the native view hierarchy, leading to more efficient and predictable animations.

In simple terms, React Native Reanimated makes it easier to create animations that feel native, fluid, and responsive. By leveraging worklet functions and shared values, animations are executed on the native thread, providing smoother and more performant user experiences.

With React Native Reanimated, you can create a wide range of animations, including transitions, gestures, complex interactions, and even physics-based animations. Its power lies in its ability to handle animations efficiently and naturally, making it a go-to choice for creating visually appealing and engaging user interfaces in React Native apps.

Import and Wrap Components:

  • Import Reanimated from react-native-reanimated in your components.
  • Wrap your entire app in Reanimated component to enable Reanimated functionalities.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
} from 'react-native-reanimated';

Some simple Animation Example

  • Start with a simple animation, like moving a component from left to right.
  • Create a Reanimated value (e.g., const translationX = useSharedValue(0);) to represent the current position.
  • Use the useAnimatedStyle hook to define the animation behaviour.
  • Apply the Animated.View component with the style prop using useAnimatedStyle.
const translationX = useSharedValue(0);

// we translate (animate) X axis here
// tips: experiment with all transform properties
const animatedStyle = useAnimatedStyle(() => {
  return {
    transform: [{ translateX: translationX.value }],
  };
});

Animate animatedStyle with a startAnimationButton in react native:

this is how we animate the translationX.value with a timing ,

Starts a time based animation.

 const startAnimation = () => {
    translationX.value = withTiming(200, { duration: 1000 });
  };

create the view that need to be returned:

<View style={styles.container}>
  <Animated.View style={[styles.box, animatedStyle]} />
  <Text onPress={startAnimation}>Move Right</Text>
</View>

style the view as your wish…. and requirement

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

Explore More Complex Animations:

  • Once you get the hang of basic animations, explore more complex ones like transitions, gestures, and sequence animations.
  • Use useDerivedValue and useAnimatedReaction for more advanced interactions.

Practice and Learn:

  • Check out the official documentation of React Native Reanimated 2: https://docs.swmansion.com/react-native-reanimated/docs/
  • Experiment with various examples and concepts to solidify your understanding.
  • Join online communities and forums to ask questions and learn from others’ experiences.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
} from 'react-native-reanimated';

const App = () => {
  const translationX = useSharedValue(0);

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [{ translateX: translationX.value }],
    };
  });

  const startAnimation = () => {
    translationX.value = withTiming(200, { duration: 1000 });
  };

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.box, animatedStyle]} />
      <Text onPress={startAnimation}>Move Right</Text>
    </View>
  );
};

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

export default App;

Bonus :Dynamic animation of two box >>

import React from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
} from 'react-native-reanimated';

const AnimatedComponents = () => {
  const buttonPressed = () => {
    // Toggle the animation state based on button press
    isAnimating.value = !isAnimating.value;
  };

  // Shared values for animation
  const isAnimating = useSharedValue(false);
  const animationDuration = 500;

  // Animated styles for the first component
  const box1Style = useAnimatedStyle(() => {
    return {
      width: isAnimating.value ? withTiming(200, { duration: animationDuration }) : withTiming(100, { duration: animationDuration }),
      height: isAnimating.value ? withTiming(200, { duration: animationDuration }) : withTiming(100, { duration: animationDuration }),
      backgroundColor: isAnimating.value ? 'blue' : 'green',
    };
  });

  // Animated styles for the second component
  const box2Style = useAnimatedStyle(() => {
    return {
      transform: [
        { translateY: isAnimating.value ? withTiming(-50, { duration: animationDuration }) : withTiming(0, { duration: animationDuration }) },
      ],
    };
  });

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.box1, box1Style]} />
      <Animated.View style={[styles.box2, box2Style]} />
      <TouchableOpacity onPress={buttonPressed} style={styles.button}>
        <Text style={styles.buttonText}>Animate</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  box1: {
    width: 100,
    height: 100,
    backgroundColor: 'green',
    marginBottom: 20,
  },
  box2: {
    width: 100,
    height: 100,
    backgroundColor: 'red',
  },
  button: {
    backgroundColor: 'purple',
    padding: 10,
    borderRadius: 8,
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default AnimatedComponents;

Refer official pages React-native reanimated 2

Reanimated

geture handler

VS Code containerized

let your curiosity works with this….!!