Enhancing Animation Performance in React Native with Reanimated

Sep 17, 2024

Enhancing Animation Performance in React Native with Reanimated

Enhance React Native animation performance with Reanimated using custom Babel plugins. Achieve smoother, faster animations on Android with easy optimizations.

Author

Biswanath Tewari
Biswanath TewariSenior Software Engineer - I

React Native is a popular framework for building cross-platform mobile applications. One of its powerful features is the ability to create smooth and performant animations. However, optimizing animation performance can be challenging. In this post, we’ll explore how to supercharge your animations in React Native using the Reanimated library and custom Babel plugins.

Get ready to make your animations smoother than butter on a hot pancake!

The Challenge

By default, when initializing any animated value using the useSharedValue hook in Reanimated, the native driver is set to false. Don't believe us? Check out the source code. This can lead to suboptimal performance, especially for complex animations. Additionally, we encountered specific performance issues on Android when animating transform properties, causing animations to lag and flicker.

Lagging animations? Ain’t nobody got time for that!

Solution 1: Custom Babel Plugin for useSharedValue

We developed a custom Babel plugin to ensure that the native driver is always set to true when using useSharedValue. This plugin automatically modifies the arguments passed to useSharedValue, enabling the native driver by default.

Here’s the code for the custom Babel plugin:

function useSharedValuePlugin({ types: t }) {
  return {
    visitor: {
      CallExpression(path) {
        if (t.isIdentifier(path.node.callee, { name: 'useSharedValue' })) {
          if (path.node.arguments.length === 1) {
            path.node.arguments.push(t.booleanLiteral(true));
          }
        }
      },
    },
  };
}

Solution 2: Handling Transform Properties on Android

For Android, we found that animations using the style's transform properties caused lagging and flickering. To overcome this, we opted to animate using deprecated props. Although the reason for the improved performance is unclear, the official documentation notes these deprecated props here.

Why go deprecated? Because sometimes, the old ways are the best ways! 😉

To automate this process, we wrote another custom Babel plugin that checks for the usage of transform properties in the useAnimatedStyle hook and converts them to deprecated props if the platform is Android.

Here’s the code for the custom Babel plugin:

function useAnimatedStylePlugin({ caller, types: t }) {
  const isAndroid = caller((caller) => caller?.platform === 'android');
  let allPropsDeprecated = true;
  const nestedVisitor = {
    ObjectProperty(path) {
      if (t.isIdentifier(path.node.key, { name: 'transform' })) {
        const parentPath = path.findParent((p) => p.isObjectExpression());
        const androidTransformProperties = ['scale', 'scaleX', 'scaleY', 'translateX', 'translateY', 'rotate'];
        for (const properties of path.node.value.elements) {
          const key = Array.isArray(properties?.properties) && properties?.properties[0]?.key;
          const value = Array.isArray(properties?.properties) && properties?.properties[0]?.value;
          if (androidTransformProperties.includes(key?.name)) {
            if (key.name === 'scale') {
              parentPath.pushContainer('properties', t.ObjectProperty({ ...key, name: 'scaleX' }, value));
              parentPath.pushContainer('properties', t.ObjectProperty({ ...key, name: 'scaleY' }, value));
            } else {
              if (key.name === 'rotate') {
                key.name = 'rotation';
              }
              parentPath.pushContainer('properties', t.ObjectProperty(key, value));
            }
          } else {
            console.warn(`${key.name} cannot be 100% converted to deprecated Android props`);
            allPropsDeprecated = false;
          }
        }
        if (allPropsDeprecated) {
          path.remove();
        }
      }
    },
  };
  return {
    visitor: {
      CallExpression(path) {
        if (isAndroid && t.isIdentifier(path.node.callee, { name: 'useAnimatedStyle' })) {
          if (path.node.arguments?.[3]?.value !== false) {
            path.traverse(nestedVisitor);
          }
          if (path.node.arguments.length === 4) {
            path.node.arguments.pop();
          }
        }
      },
    },
  };
}

A Brief Overview of Babel and AST

Babel

Babel is a popular JavaScript compiler that helps you use next-generation JavaScript, today. It allows developers to write modern JavaScript code that can run on older browsers or environments by transforming it into a backward-compatible version. Babel also provides powerful plugins and presets that enable a wide range of functionalities, including code optimization and transformation.

Think of Babel as your code’s personal translator, ensuring it speaks every browser’s language!

Abstract Syntax Tree (AST)

An Abstract Syntax Tree (AST) is a tree representation of the structure of source code. It breaks down the code into its syntactical elements, such as statements, expressions, and declarations. This structure allows tools like Babel to analyze and transform the code. By traversing the AST, Babel plugins can modify specific parts of the code, enabling powerful transformations and optimizations.

We are going to use babel to our advantage here to manipulate the AST as per our needs.

How It Works

useSharedValuePlugin

The plugin works by traversing the abstract syntax tree (AST) of your code and looking for calls to useSharedValue. When it finds one, it checks the number of arguments passed. If only one argument is present, the plugin adds a second argument, setting the native driver to true.

useAnimatedStylePlugin

This plugin detects the usage of transform properties in the useAnimatedStyle hook and converts them to deprecated props for better performance on Android. It traverses the AST to find transform properties and replaces them with their deprecated equivalents.

Implementation Steps

  1. Install Babel and the Plugins: First, ensure that you have Babel installed in your project. Then, add the custom plugins to your Babel configuration.
npm install --save-dev @babel/core @babel/preset-env
  1. Configure Babel: Add the custom plugins to your Babel configuration file (e.g., babel.config.js).
module.exports = {
  presets: ['@babel/preset-env'],
  plugins: [useSharedValuePlugin, useAnimatedStylePlugin],
};
  1. Add the Plugins: Save the custom plugin codes in the babel.config.js file or you can save them in separate files as well.

Benefits

By automatically setting the native driver to true and converting transform properties to deprecated props on Android, these plugins ensure that your animations run more smoothly and efficiently. This is particularly beneficial for complex animations that can be resource-intensive.

Your users will be like: “Wow, how did they make these animations so smooth?”

Conclusion

Optimizing animation performance in React Native can significantly enhance the user experience. By using custom Babel plugins to handle useSharedValue and transform properties, you can achieve smoother and more performant animations. Feel free to try out these approaches in your projects and experience the performance improvements firsthand.

Happy coding, and may your animations be ever so smooth!

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Taming Elasticsearch at Scale
Oct 13, 2026

Taming Elasticsearch at Scale

Optimize Elasticsearch for millions of records with better pagination, leaner payloads, efficient filtering, faster ingestion, and frontend techniques that keep search responsive with increase in data.

Insight
Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide
Oct 13, 2026

Deep Linking for Mobile Apps(React Native) with NestJs, AWS CloudFront, S3 & ALB: A Complete Guide

Build a self-hosted deep linking and referral system for React Native without a third-party SDK. This guide covers Android App Links, iOS Universal Links, an S3 and CloudFront setup, and a NestJS backend that routes users to the right app store.

Insight
How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform
Oct 12, 2026

How We Engineered a Three-Path Reward Processing System for a Real-Time Sports Platform

This blog explains how a real-time sports platform uses synchronous, asynchronous, and scheduled processing paths to handle rewards without slowing down the player experience.

Insight
Building an MCP-Powered QA Agent
Oct 12, 2026

Building an MCP-Powered QA Agent

Build an MCP QA agent that runs Playwright tests, validates APIs, and analyzes failures through a controlled, auditable tool layer with human approval.

Insight
From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline
Oct 9, 2026

From Test Failure to Root Cause: Building an AI-Assisted Playwright Failure Analysis Pipeline

This blog explains how an AI-assisted Playwright pipeline can analyze test failure evidence, identify probable root causes, and support human-validated debugging.

Insight
The Model Context Protocol: From First Call to Production
Oct 8, 2026

The Model Context Protocol: From First Call to Production

This blog explains how Model Context Protocol (MCP) works, from tool discovery and execution to OAuth authorization, security controls, and production deployment.

Insight
Stop Automating Everything: A Balanced Quality Engineering Approach to Testing
Oct 8, 2026

Stop Automating Everything: A Balanced Quality Engineering Approach to Testing

Balanced quality engineering places automation, API testing, exploratory work, and AI where each gives the most value, so teams ship faster without trading away user-perceived quality.

Footer

The Right Conversation Can

Save You Six Months.

Book a Call