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 TewariBiswanath TewariSenior Software Engineer - I
Enhancing Animation Performance in React Native with Reanimated

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

RELATED ARTICLES

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
The Bug That Doesn't Show Up in Code Review: Why Your Flutter Web App Reloads on Safari
A real-world look at how oversized images can trigger Safari reloads and iOS crashes in Flutter apps and how smarter image decoding prevents them.
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
From Prompting to Process: What Changed When Flutter Shipped Agent Skills
This blog explores how Flutter Agent Skills improve AI-assisted development by combining official framework workflows with project-specific guidance for more consistent development.
Why Everything Your AI Builds Looks the Same
Why Everything Your AI Builds Looks the Same
This blog explores why AI-generated interfaces often look alike and explains how design systems, product context, and reusable engineering practices help teams build distinctive, scalable
How We Built the Missing Bridge from Code to Figma
Technology

Jul 10, 2026

How We Built the Missing Bridge from Code to Figma
This blog explores how AI-generated React apps get turned into fully editable, designer-ready Figma files by reading React Fiber instead of the DOM.
Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
Technology

Jun 27, 2026

Building a Resilient Hybrid-Cloud Network with WireGuard HA, Route-Based Failover, and Deep Observability
A practical breakdown of building resilient AWS-to-on-premises connectivity with WireGuard HA, active-standby failover, and deep packet-forwarding observability.
We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
Technology

Jun 19, 2026

We Built a 114-Second AWS-to-Azure Failover. Here’s What We Learned
A practical guide to building a 114-second multi-cloud disaster recovery failover between AWS and Azure — what we built, what broke, and what we learned.
Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
Technology

Jun 12, 2026

Cloud-Native and Cloud-Agnostic Are Not Ideologies; They Are Business-Stage Decisions
This blog explains how organizations can balance speed, scalability, and operational flexibility as they grow from startup to enterprise scale.

The Right Conversation Can Save You Six Months.

Whether you’re navigating AI adoption, modernizing legacy systems, or scaling a product - we start by listening. No pitch deck. No template. A real conversation.