Learn React Native Β· 12/15

Animations & Gestures

11 min read

Hey there, future animation wizard! πŸ§™β€β™‚οΈ Welcome to the magical world of movement and interaction in React Native. Ever wondered how apps feel so alive, with things smoothly sliding, popping, and responding to your every touch? That's what we're about to uncover.

Strap in, because you're about to learn how to breathe life into your user interfaces. We'll start with the basics and then level up to some seriously slick, professional-grade animations and gestures. Ready? Let's get those pixels dancing! πŸ’ƒ

Animations & Gestures πŸ€Έβ€β™€οΈ

In the land of mobile apps, a static, lifeless interface is like a movie with no sound. It just doesn't feel right. Users expect and love apps that respond to their touch in a smooth and intuitive way. This is where animations and gestures come in. They provide visual feedback, guide the user's attention, and frankly, make your app a joy to use.

But here's the catch: making animations that are smooth and performant can be a real head-scratcher. If not done right, you can end up with janky, stuttering animations that make your app feel slow and clunky. Nobody wants that!

This guide will walk you through the best tools in the React Native ecosystem to create buttery-smooth animations and handle complex user gestures with ease.


1. The Animated API: Bringing UI to Life ✨

First up, let's talk about the OG of React Native animation: the Animated API. It's built right into React Native, so you don't need to install anything extra to get started.

The Problem: How can we change the properties of a component over time in a performant way? For example, how do we smoothly move a box from left to right, or fade in a new element?

The Solution: The Animated API provides a way to create time-based animations that are highly optimized. It works by creating a declarative relationship between an input (like a value changing over time) and an output (a style property of a component).

Under the Hood πŸ•΅οΈβ€β™€οΈ

The Animated API works by sending the animation details over to the native side (the UI thread where your app's interface is rendered). This means the animation can run independently of the JavaScript thread, where your app's logic is running. Why is this a big deal? If your JavaScript thread is busy with other tasks, your animation won't stutter. It's like having a dedicated "animation manager" that keeps things running smoothly, no matter what else is happening.

Core Concepts

  • Animated.Value: Think of this as a special kind of variable that holds a single numeric value you want to animate. You can't just change it directly like a regular variable. Instead, you use animation functions to "drive" its value over time.
  • Animated.View, Animated.Text, Animated.Image: To make a component animatable, you need to wrap it with one of these special Animated components. This tells React Native that some of this component's style properties will be controlled by an Animated.Value.
  • Animation Functions (Animated.timing, Animated.spring, Animated.decay): These are the functions that actually change the Animated.Value over a period.
    • timing: Animates a value over a specified duration with a particular easing function (the rate of change of the animation).
    • spring: Creates a simple spring physics-based animation. It gives a bouncy, natural feel.
    • decay: Animates with an initial velocity and gradually slows to a stop.

Let's See Some Code! πŸ’»

Here's a simple example of how to fade in a View:

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

const FadeInView = () => {
  // Initial value for opacity: 0
  const fadeAnim = useRef(new Animated.Value(0)).current;

  const fadeIn = () => {
    // Will change fadeAnim value to 1 in 5 seconds
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 5000,
      useNativeDriver: true, // <-- Add this for performance!
    }).start();
  };

  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Animated.View
        style={{
          width: 250,
          height: 50,
          backgroundColor: 'powderblue',
          opacity: fadeAnim, // Bind opacity to animated value
        }}
      />
      <View style={{marginTop: 20}}>
        <Button title="Fade In" onPress={fadeIn} />
      </View>
    </View>
  );
}

export default FadeInView;

What's with useNativeDriver: true? πŸ€”
This little property is a powerhouse for performance. When you set it to true, the animation is sent over to the native UI thread and runs there entirely. This frees up your JavaScript thread and results in much smoother animations. You should always try to use it! However, it only works with non-layout properties like transform and opacity.


2. React Native Reanimated: 60FPS Smoothness πŸš€

While the Animated API is great, sometimes you need more power and control, especially for gesture-based animations. This is where React Native Reanimated swoops in to save the day!

The Problem: Complex animations that are tied to user gestures (like dragging an element around the screen) can sometimes be janky with the Animated API because of the back-and-forth communication between the JavaScript and UI threads (known as "crossing the bridge").

The Solution: React Native Reanimated allows you to define your animations entirely on the UI thread, eliminating the need to cross the bridge for every frame of the animation. This results in incredibly smooth, 60 frames-per-second (FPS) animations, even for the most complex scenarios.

Installation and Setup

Getting started with Reanimated requires a bit more setup than the Animated API.

First, you'll need to install the package.

bash
# For Expo
npx expo install react-native-reanimated

# For React Native CLI
npm install react-native-reanimated
cd ios && pod install && cd ..

Next, you need to add the Reanimated Babel plugin to your babel.config.js. This plugin is the secret sauce that allows Reanimated to do its magic. Make sure it's the last plugin in the list!

javascript
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    // ... other plugins
    'react-native-reanimated/plugin', // Must be last
  ],
};

Finally, clear your bundler cache to make sure the new plugin is picked up.

bash
npm start -- --reset-cache

Core Concepts

  • Shared Values (useSharedValue): Similar to Animated.Value, but these can be accessed and modified on the UI thread. They are the foundation of Reanimated animations.
  • Animated Styles (useAnimatedStyle): This hook is used to create styles that react to changes in shared values. The code inside useAnimatedStyle runs on the UI thread, so it can update your component's styles without any delay.
  • Animation Helpers (withTiming, withSpring): These are functions that you use to change shared values over time. They are similar to the animation functions in the Animated API but are designed to work on the UI thread.
  • Worklets: A worklet is a small piece of JavaScript code that can be moved to run on the UI thread. Reanimated uses worklets extensively under the hood. You don't always need to write your own, but it's good to know they exist.

Code Example: A Bouncing Ball πŸ€

javascript
import React from 'react';
import { View, StyleSheet } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  withRepeat,
} from 'react-native-reanimated';

export default function BouncingBall() {
  const translateY = useSharedValue(0);

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

  React.useEffect(() => {
    translateY.value = withRepeat(withSpring(100), -1, true);
  }, []);

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.ball, animatedStyles]} />
    </View>
  );
}

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

In this example, the ball will bounce up and down forever, and the animation will be super smooth because it's all happening on the UI thread.


3. React Native Gesture Handler: Swipes & Pinches 🀏

Animations are great, but what about when you want the user to drive the animation with their fingers? That's where React Native Gesture Handler comes in.

The Problem: The default touch system in React Native can sometimes be a bit finicky, especially when you have multiple gestures happening at once (like a swipeable list inside a scrollable screen). The Gesture Handler library provides a more robust and reliable way to handle gestures.

The Solution: It provides a set of components that can recognize and manage complex gestures, and it's designed to work seamlessly with React Native Reanimated.

Installation

bash
# For Expo
npx expo install react-native-gesture-handler

# For React Native CLI
npm install react-native-gesture-handler
cd ios && pod install && cd ..

Then, you need to wrap your entire app in GestureHandlerRootView. This is usually done in your App.js or index.js file.

javascript
import { GestureHandlerRootView } from 'react-native-gesture-handler';

export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      {/* Your app's content */}
    </GestureHandlerRootView>
  );
}

Core Concepts

  • GestureDetector and Gesture: You use GestureDetector to wrap the component you want to be able to receive gestures. The Gesture object is where you define the type of gesture you're looking for (e.g., Gesture.Pan(), Gesture.Tap()).
  • Gesture Callbacks (onUpdate, onEnd, etc.): These are functions that get called at different stages of the gesture. For example, onUpdate is called every time the user's finger moves during a pan gesture.

Code Example: Dragging a Box πŸ“¦

javascript
import React from 'react';
import { StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
} from 'react-native-reanimated';

export default function DraggableBox() {
  const isPressed = useSharedValue(false);
  const offset = useSharedValue({ x: 0, y: 0 });

  const animatedStyles = useAnimatedStyle(() => {
    return {
      transform: [
        { translateX: offset.value.x },
        { translateY: offset.value.y },
        { scale: isPressed.value ? 1.2 : 1 },
      ],
      backgroundColor: isPressed.value ? 'yellow' : 'blue',
    };
  });

  const panGesture = Gesture.Pan()
    .onBegin(() => {
      isPressed.value = true;
    })
    .onUpdate((e) => {
      offset.value = {
        x: e.translationX,
        y: e.translationY,
      };
    })
    .onEnd(() => {
      isPressed.value = false;
    });

  return (
    <GestureDetector gesture={panGesture}>
      <Animated.View style={[styles.box, animatedStyles]} />
    </GestureDetector>
  );
}

const styles = StyleSheet.create({
  box: {
    width: 100,
    height: 100,
    borderRadius: 20,
    cursor: 'grab',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Here, we're creating a pan gesture. When the user starts dragging the box, onBegin fires. As they drag, onUpdate fires continuously, updating the offset shared value. When they let go, onEnd fires.


4. Building a Real-World Animation (e.g., Swipeable Cards) πŸƒ

Now, let's put everything we've learned together to build something you'll see in tons of apps: swipeable cards, like in a dating app.

The Goal: We want to be able to swipe a card left or right. If we swipe it far enough, it should fly off the screen. If we don't swipe it far enough, it should spring back to the center.

This will involve:

  • Using React Native Gesture Handler to detect the swipe.
  • Using React Native Reanimated to animate the card's position and rotation based on the swipe.

Here's a simplified version of how you might approach this:

javascript
import React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  interpolate,
  Extrapolate,
} from 'react-native-reanimated';

const { width: screenWidth } = Dimensions.get('window');
const swipeThreshold = screenWidth * 0.5;

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

  const panGesture = Gesture.Pan()
    .onUpdate((event) => {
      translateX.value = event.translationX;
    })
    .onEnd(() => {
      if (Math.abs(translateX.value) > swipeThreshold) {
        translateX.value = withSpring(
          Math.sign(translateX.value) * screenWidth
        );
      } else {
        translateX.value = withSpring(0);
      }
    });

  const animatedStyle = useAnimatedStyle(() => {
    const rotate = interpolate(
      translateX.value,
      [-screenWidth / 2, screenWidth / 2],
      [-15, 15],
      Extrapolate.CLAMP
    );

    return {
      transform: [
        { translateX: translateX.value },
        { rotate: `${rotate}deg` },
      ],
    };
  });

  return (
    <View style={styles.container}>
      <GestureDetector gesture={panGesture}>
        <Animated.View style={[styles.card, animatedStyle]} />
      </GestureDetector>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  card: {
    width: 300,
    height: 400,
    backgroundColor: 'white',
    borderRadius: 20,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
});

export default SwipeableCard;

Breaking it down:

  • We track the horizontal swipe distance with the translateX shared value.
  • In the onUpdate of the pan gesture, we update translateX to follow the user's finger.
  • In onEnd, we check if the swipe distance is greater than our swipeThreshold. If it is, we use withSpring to animate the card off the screen. Otherwise, we spring it back to the center.
  • We use the interpolate function to map the translateX value to a rotation value, so the card tilts as you swipe it.

You've Leveled Up! πŸ†

And there you have it! You've gone from zero to hero in React Native animations and gestures. You've seen how to create simple animations with the Animated API, how to achieve buttery-smooth performance with Reanimated, and how to handle user input with Gesture Handler.

The world of animations and gestures is vast and full of creative possibilities. Don't be afraid to experiment and have fun with it!

For Further Reading πŸ“š

Challenge

Challenge: Build a Swipeable Card Component

Your task is to implement the gesture and animation logic for a swipeable card component using react-native-reanimated and react-native-gesture-handler.

The component should allow a user to drag a card around the screen. When the user releases the card, it should smoothly spring back to its original centered position.

Requirements:

  1. Initialize two shared values, translateX and translateY, to track the card's position.
  2. Create a pan gesture handler using Gesture.Pan().
  3. In the gesture's onUpdate callback, update translateX and translateY with the gesture's current translation values.
  4. In the gesture's onEnd callback, animate both translateX and translateY back to 0 using the withSpring animation helper.
  5. Create an animated style using useAnimatedStyle that applies the translateX and translateY transformations to the card.
  6. Bonus: Use the interpolate function within your animated style to make the card rotate slightly as it is dragged horizontally. For example, map a horizontal translation range of [-150, 150] to a rotation range of ['-10deg', '10deg'].

Expected result

The final code should be a complete and functional SwipeableCard component. The solution must correctly implement the following:

  1. translateX and translateY are initialized using useSharedValue(0).
  2. The onUpdate callback of the pan gesture sets translateX.value = event.translationX and translateY.value = event.translationY.
  3. The onEnd callback sets translateX.value = withSpring(0) and translateY.value = withSpring(0).
  4. The useAnimatedStyle hook returns an object containing a transform property.
  5. The transform property is an array of transformation objects: [{ translateX: translateX.value }, { translateY: translateY.value }, { rotateZ: ... }].
  6. The rotateZ value is calculated using interpolate, mapping the translateX.value to a degree-based rotation string. A correct implementation would look like:
    javascript
    const rotation = interpolate(
      translateX.value,
      [-150, 0, 150],
      [-10, 0, 10],
      Extrapolate.CLAMP
    );
    
    return {
      transform: [
        { translateX: translateX.value },
        { translateY: translateY.value },
        { rotateZ: `${rotation}deg` },
      ],
    };
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.