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
Building Local LLMs Using Dart FFI And llama.cpp: Beyond Wrapper Packages
Sep 11, 2026

Building Local LLMs Using Dart FFI And llama.cpp: Beyond Wrapper Packages

Build local LLMs in Flutter with Dart FFI and llama.cpp, and see how native bridges, GGUF models, memory management, and token streaming enable private, on-device AI.

Insight
My Flutter App Froze With Three Photos on Screen. Here's What I Was Doing Wrong
Sep 11, 2026

My Flutter App Froze With Three Photos on Screen. Here's What I Was Doing Wrong

This blog explains how rethinking Flutter’s image-processing architecture fixed severe performance issues and improved rendering efficiency.

Insight
Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15
Sep 10, 2026

Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15

This blog explains how to build a production-ready canvas editor with Konva.js, React, and Next.js, covering architecture, performance, and key engineering decisions.

Insight
What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust
Sep 8, 2026

What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust

This blog explores the architecture, security, performance, and documentation lessons from migrating a legacy PHP/Laravel banking platform to NestJS.

Insight
Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs
Sep 7, 2026

Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs

This blog explains how to build responsive video thumbnail scrubbing in the browser for local files and HLS streams, covering frame extraction, caching, and performance trade-offs.

Insight
The Agent Can See Your App. How Often Can It Look?
Sep 4, 2026

The Agent Can See Your App. How Often Can It Look?

AI coding agents can now interact with mobile apps, but their effectiveness depends on iteration speed. This blog explores how React Native architecture influences feedback loops and AI-driven developer productivity.

Insight
Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists
Sep 1, 2026

Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists

Learn how to turn design JSON into interactive, video-enabled cards using overlays, smart media controls, caching, and virtualization without slowing down high-cardinality feeds.

The Right Conversation Can

Save You Six Months.

Book a call