Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Historical Context
3.
What is React Native Reanimated?
4.
Core Concepts of React Native Reanimated
5.
Installation and Setup
5.1.
Advanced Usage
5.2.
Combining Gestures and Animations
6.
Advantages of React Native Reanimated
6.1.
Performance
6.2.
Flexibility
7.
Disadvantages of React Native Reanimated
8.
Edge Cases and Their Implications
8.1.
Practical Applications of React Native Reanimated
8.2.
The Future of React Native Reanimated
9.
Frequently Asked Questions
9.1.
How does React Native Reanimated compare to other animation libraries?
9.2.
Is React Native Reanimated suitable for beginners?
9.3.
How does React Native Reanimated handle gesture interactions?
9.4.
How does react-native reanimated differ from react-native's built in Animated API?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

React Native Reanimated

Author Rahul Singh
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In the sprawling domain of mobile application development, delivering a seamless, interactive user experience is paramount. One library that significantly contributes to achieving this objective is React Native Reanimated. It stands as a cornerstone for developers aiming to craft fluid animations and gestures in their applications. 

react native reanimated

This article endeavors to unravel the essence of React Native Reanimated, shedding light on its capabilities in enriching mobile UIs.

Historical Context

React Native Reanimated made its debut as an attempt to bridge the gap between high-performance animations and ease of development. Over time, it has morphed into a vital asset for React Native developers, presenting a superior alternative to earlier animation libraries. Its evolution embodies the relentless pursuit of enhanced performance and user-centric interfaces.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is React Native Reanimated?

React Native Reanimated is a library for React Native designed to build smooth and complex animations and interactions in mobile applications. It extends the basic animation capabilities of React Native, offering more flexibility and control while improving performance. This library allows for declarative animations in the React Native environment, enabling smoother and more responsive user experiences, especially in gesture-based interactions or complex animation sequences. Reanimated is particularly valued for its ability to run animations on the UI thread without crossing the bridge into JavaScript, reducing lag and jitter in animations.

Core Concepts of React Native Reanimated

Worklets: Worklets in React Native Reanimated are a novel concept. They facilitate running animations on a different thread, ensuring the main thread remains unblocked, which is crucial for maintaining a high frame rate.

// Defining a worklet
worklet function myWorklet() {
  'worklet';
  // ...
}

 

Shared Values: Shared values act as a bridge between JavaScript and native realms, allowing seamless communication, which is pivotal for orchestrating animations.

import Animated from 'react-native-reanimated';

const sharedValue = Animated.sharedValue(0);  // Initial value

 

Animation Functions: Animation functions are the building blocks that empower developers to create diverse animations effortlessly.

import Animated, { Easing, withSpring } from 'react-native-reanimated';


const animate = (toValue) => {
  return Animated.timing(toValue, {
    duration: 1000,
    easing: Easing.inOut(Easing.ease),
  });
};

 

Gesture Handlers: Gesture handling is streamlined through integration with React Native Gesture Handler, enabling a natural feel to user interactions.

import { PanGestureHandler } from 'react-native-gesture-handler';
import Animated, { useAnimatedGestureHandler } from 'react-native-reanimated';


const gestureHandler = useAnimatedGestureHandler({
  onStart: (_, ctx) => { /* ... */ },
  onActive: (_, ctx) => { /* ... */ },
  onEnd: (_, ctx) => { /* ... */ },
});

 

Usage of PanGestureHandler

<PanGestureHandler onGestureEvent={gestureHandler} />;

Installation and Setup

Installation

Embarking on the journey with React Native Reanimated begins by installing the library using npm or Yarn.

# Installation command

npm install react-native-reanimated

 

Initial Setup:

Post-installation, some configurations are necessary to kickstart the usage of this library in your project.

// Initial setup command for linking native modules

npx pod-install

Advanced Usage

Creating Custom Animations:

The flexibility of React Native Reanimated shines when crafting custom animations, allowing developers to bring their creative visions to life.

import Animated, { useSharedValue, useAnimatedStyle } from 'react-native-reanimated';


const CustomAnimation = () => {
  const offset = useSharedValue(0);


  const animatedStyles = useAnimatedStyle(() => {
    return {
      transform: [{ translateY: offset.value * 100 }],
    };
  });


  return <Animated.View style={animatedStyles} />;
};

export default CustomAnimation;

Combining Gestures and Animations

Melding gestures with animations unveils a realm of possibilities in creating intuitive, interactive user interfaces.

 

import React from 'react';
import { View } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedGestureHandler,
  useAnimatedStyle,
  withSpring,
} from 'react-native-reanimated';
import { PanGestureHandler } from 'react-native-gesture-handler';


const DraggableBox = () => {
  // Shared values to hold the translation values
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);

 

 Gesture handler to update the translation values based on the gesture

 const gestureHandler = useAnimatedGestureHandler({

    onStart: (_, ctx) => {
      // Storing the starting position
      ctx.startX = translateX.value;
      ctx.startY = translateY.value;
    },
    onActive: (event, ctx) => {
      // Updating the translation values during the gesture
      translateX.value = ctx.startX + event.translationX;
      translateY.value = ctx.startY + event.translationY;
    },
    onEnd: () => {
      // Springing back to the original position when the gesture ends
      translateX.value = withSpring(0);
      translateY.value = withSpring(0);
    },
  });

 

 Animated style to apply the translation values

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


  return (
    <PanGestureHandler onGestureEvent={gestureHandler}>
      <Animated.View
        style={[
          {
            width: 100,
            height: 100,
            backgroundColor: 'blue',
          },
          animatedStyle,
        ]}
      />
    </PanGestureHandler>
  );
};


export default DraggableBox;

 

In this example:

  • useSharedValue is used to create shared values for translateX and translateY.
     
  • useAnimatedGestureHandler is used to create a gesture handler that updates the translation values based on the gesture.
     
  • useAnimatedStyle is used to create an animated style that applies the translation values.
     
  • PanGestureHandler from 'react-native-gesture-handler' is used to handle the pan gesture.
     
  • withSpring is used to create a spring animation that brings the box back to its original position when the gesture ends.

Advantages of React Native Reanimated

Performance

The performance gains with React Native Reanimated are noticeable. Animations run smoothly, providing a polished user experience.

javascript
import React from 'react';
import { View } from 'react-native';
import Animated, { Easing, withSpring, withTiming } from 'react-native-reanimated';


const FadeInAnimation = () => {
  const opacity = new Animated.Value(0);  // initial value


  const fadeIn = () => {
    opacity.value = withTiming(1, {
      duration: 2000,
      easing: Easing.ease,
    });
  };

 

 Trigger the animation on component mount

  React.useEffect(() => {
    fadeIn();
  }, []);


  const animatedStyles = {
    opacity: opacity.value,
  };


  return (
    <Animated.View style={[{ width: 100, height: 100, backgroundColor: 'blue' }, animatedStyles]} />
  );
};


export default FadeInAnimation;

Flexibility

React Native Reanimated provides a flexible API to create complex animations. Here’s an example showcasing a draggable box which springs back to its original position after being released.

import React from 'react';
import { View } from 'react-native';
import Animated, { useSharedValue, useAnimatedStyle, useAnimatedGestureHandler, withSpring } from 'react-native-reanimated';
import { PanGestureHandler } from 'react-native-gesture-handler';


const DraggableBox = () => {
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);


  const gestureHandler = useAnimatedGestureHandler({
    onStart: (_, ctx) => {
      ctx.startX = translateX.value;
      ctx.startY = translateY.value;
    },
    onActive: (event, ctx) => {
      translateX.value = ctx.startX + event.translationX;
      translateY.value = ctx.startY + event.translationY;
    },
    onEnd: () => {
      translateX.value = withSpring(0);
      translateY.value = withSpring(0);
    },
  });


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


  return (
    <PanGestureHandler onGestureEvent={gestureHandler}>
      <Animated.View style={[{ width: 100, height: 100, backgroundColor: 'red' }, animatedStyles]} />
    </PanGestureHandler>
  );
};
export default DraggableBox;

 

In the first example, withTiming function is used to smoothly transition the opacity of a box from 0 to 1 over a duration of 2 seconds. In the second example, a PanGestureHandler from 'react-native-gesture-handler' is used alongside useAnimatedGestureHandler and withSpring from React Native Reanimated to create a draggable box that springs back to its original position when released. These examples illustrate the performance and flexibility that React Native Reanimated offers for creating interactive animations.

Disadvantages of React Native Reanimated

Lets understand the disadvantages of using react native reanimated:

Learning Curve:

For developers new to animations, there's a steep learning curve. The library requires a solid grasp of animation principles and React Native.

Setup Complexity:

The setup can be intricate compared to other libraries, which might deter some developers.

Edge Cases and Their Implications

Certain edge cases might arise while working with React Native Reanimated, especially when dealing with complex gestures and animations. Handling these edge cases efficiently is crucial to ensure a seamless user experience.

Practical Applications of React Native Reanimated

React Native Reanimated finds its application in myriad real-world scenarios. Whether it's creating swipeable list items, collapsible headers, or playful loading animations, the library empowers developers to elevate the user interface of their applications.

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  useAnimatedGestureHandler,
  withSpring,
} from 'react-native-reanimated';
import { PanGestureHandler } from 'react-native-gesture-handler';


const SwipeableListItem = () => {
  const translateX = useSharedValue(0);


  const gestureHandler = useAnimatedGestureHandler({
    onStart: (_, ctx) => {
      ctx.startX = translateX.value;
    },
    onActive: (event, ctx) => {
      translateX.value = ctx.startX + event.translationX;
    },
    onEnd: () => {
      if (translateX.value < -100) {
        // Snap to the left if swiped more than 100px to the left
        translateX.value = withSpring(-200);
      } else {
        // Otherwise, snap back to 0
        translateX.value = withSpring(0);
      }
    },
  });


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


  return (
    <View style={{ marginVertical: 10 }}>
      <View style={{ position: 'absolute', right: 0, flexDirection: 'row' }}>
        <TouchableOpacity style={{ backgroundColor: 'blue', padding: 20 }}>
          <Text style={{ color: 'white' }}>Action 1</Text>
        </TouchableOpacity>
        <TouchableOpacity style={{ backgroundColor: 'red', padding: 20 }}>
          <Text style={{ color: 'white' }}>Action 2</Text>
        </TouchableOpacity>
      </View>
      <PanGestureHandler onGestureEvent={gestureHandler}>
        <Animated.View
          style={[
            {
              height: 60,
              backgroundColor: 'white',
              justifyContent: 'center',
              paddingHorizontal: 20,
            },
            animatedStyle,
          ]}
        >
          <Text>Swipe me left</Text>
        </Animated.View>
      </PanGestureHandler>
    </View>
  );
};


export default SwipeableListItem;

 

In this example:

  • PanGestureHandler from 'react-native-gesture-handler' is used to handle the swipe gestures.
     
  • useSharedValue is used to create a shared value for translateX to hold the translation value.
     
  • useAnimatedGestureHandler is used to create a gesture handler that updates translateX based on the gesture.
     
  • useAnimatedStyle is used to create an animated style that applies the translateX translation value.
     
  • withSpring is used to create a spring animation to either snap the item to the left, revealing the action buttons, or snap it back to its original position based on the swipe distance.

The Future of React Native Reanimated

With the relentless pace of development in the React Native ecosystem, React Native Reanimated is poised for continual growth. The advent of new features and improvements is anticipated, making it an exciting library to keep an eye on.

Must Read, React Native Paper, React devtools

Frequently Asked Questions

How does React Native Reanimated compare to other animation libraries?

React Native Reanimated stands a cut above owing to its performance optimization and flexibility in creating complex animations.

Is React Native Reanimated suitable for beginners?

While it has a steep learning curve, with the right resources and persistence, mastering React Native Reanimated is within reach.

How does React Native Reanimated handle gesture interactions?

Through seamless integration with React Native Gesture Handler, gesture interactions are handled efficiently, contributing to a natural user experience.

How does react-native reanimated differ from react-native's built in Animated API?

React Native Reanimated offers more advanced and efficient animation capabilities than React Native's built-in Animated API. It enables smoother, more complex animations by running them on the UI thread, thus reducing lag and improving performance, especially for gesture-based interactions.

Conclusion

Unfolding the capabilities of React Native Reanimated unveils its immense potential in crafting fluid, interactive user interfaces in React Native applications. Its extensive feature set, coupled with performance optimization, makes it a prized asset for developers. Embracing React Native Reanimated is a stride towards creating engaging, user-centric mobile applications that resonate with modern-day users.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Happy Learning!

Previous article
React Native vs Swift
Next article
useImperativeHandle
Live masterclass