FEATURES OF WORKING WITH ANIMATION IN REACT NATIVE USING THE REANIMATED LIBRARY

FEATURES OF WORKING WITH ANIMATION IN REACT NATIVE USING THE REANIMATED LIBRARY
Ramazanov I.
Цитировать:
Ramazanov I. FEATURES OF WORKING WITH ANIMATION IN REACT NATIVE USING THE REANIMATED LIBRARY // Universum: технические науки : электрон. научн. журн. 2025. 2(131). URL: https://7universum.com/ru/tech/archive/item/19180 (дата обращения: 19.04.2025).
Прочитать статью:
DOI - 10.32743/UniTech.2025.131.2.19180

 

ABSTRACT

The article focuses on the application of the Reanimated library for creating animations in React Native, which enhances interactions with mobile interfaces. Animation is a crucial element in the perception of an application, as its smoothness, responsiveness to user actions, and interactivity influence the overall impression of the app experience. 

The tools for animations in React Native, such as the standard Animated library, are examined. When implementing more complex animation effects with high performance requirements, these solutions encounter certain limitations. The Reanimated library allows computations to be performed at the native level, reducing delays and making transitions smoother. This makes it an effective tool for implementing high-performance animations. 

The purpose of the article is to analyze the capabilities of the Reanimated library and identify its advantages compared to other approaches. The methodology involves a theoretical study of documentation and testing the library in projects. Examples of animations, such as style changes, scrolling, and gestures, are considered. Performance testing demonstrates the advantages of Reanimated over the Animated library. 

The test results show that using Reanimated improves animation performance. Performing computations at the native level reduces delays, making animations smooth and responsive, even with complex visual effects or frequent gesture usage. The library provides precise control over animations, allowing solutions to be tailored to diverse tasks. 

This work will be useful for developers using React Native who face limitations with standard animation tools. The material is of interest to those aiming to improve the performance of mobile app interfaces and create animations that do not compromise the overall application speed. In conclusion, it can be noted that using Reanimated enhances performance, increases interface flexibility, and improves the user experience in mobile applications.

АННОТАЦИЯ

Статья посвящена применению библиотеки Reanimated для создания анимаций в React Native, что улучшает взаимодействие с мобильными интерфейсами. Анимация является важным элементом восприятия приложения, поскольку её плавность, реакция на действия пользователя, интерактивность оказывают влияние на общее впечатление от работы с приложением.

Рассматриваются инструменты для анимаций в React Native, такие как стандартная библиотека Animated. При реализации более сложных анимационных эффектов с высоким уровнем производительности эти решения сталкиваются с ограничениями. Библиотека Reanimated позволяет выполнять вычисления на нативном уровне, что снижает задержки, делает переходы более плавными. Это делает её эффективным инструментом для реализации высокопроизводительных анимаций.

Цель статьи заключается в проведении анализа возможностей библиотеки Reanimated, выявлении её преимуществ по сравнению с другими подходами.  Методология работы включает теоретическое изучение документации, тестирование библиотеки в проектах. Рассматриваются примеры анимаций: изменение стилей, прокрутка, жесты. Проводится тестирование производительности, что демонстрирует преимущества Reanimated перед библиотекой Animated.

Результаты тестов показывают, что использование Reanimated улучшает производительность анимаций. Выполнение вычислений на нативном уровне снижает задержки, анимации становятся плавными, отзывчивыми, даже при сложных визуальных эффектах или частом применении жестов. Библиотека даёт точный контроль над анимациями, что позволяет адаптировать решения под разнообразные задачи.

Данная работа будет полезна разработчикам, использующим React Native, сталкивающимся с ограничениями стандартных инструментов анимации. Материал интересен тем, кто стремится повысить производительность интерфейсов мобильных приложений, создавать анимации, не влияющие на общую скорость работы приложения. В заключение можно отметить, что использование Reanimated позволяет улучшить производительность, повысить гибкость интерфейсов, улучшить пользовательский опыт в мобильных приложениях.

 

Keywords: React Native, animation, Reanimated library, performance, user interface, mobile applications, gestures, optimization.

Ключевые слова: React Native, анимация, библиотека Reanimated, производительность, пользовательский интерфейс, мобильные приложения, жесты, оптимизация.

 

Introduction

Animation enhances interaction with mobile applications, improving the usability and intuitiveness of interfaces. In the React Native ecosystem, animation elements ensure smooth transitions, precise gestures, and expressive visual effects, creating a flexible and responsive application framework. However, the Animated library built into the framework has limitations in handling gestures and complex dynamic interactions. These limitations negatively impact the performance and responsiveness of the interface.

In response to these challenges, the Reanimated library was developed, providing advanced tools for implementing animations. It transfers computations from the JavaScript level to the native level, reducing the load on the main thread and improving the application's efficiency. This approach enables the creation of complex animation effects, which is particularly relevant for projects with intensive use of graphical elements.

With the increasing demands on mobile technologies, the need for efficient animation handling is also growing. The advancement of hardware capabilities in mobile devices and rising user expectations for interface quality make it essential to use tools that ensure stable performance under heavy loads. The Reanimated library optimizes resources, enabling the creation of animations that are critically important for performance-oriented applications.

The purpose of this article is to analyze the capabilities of the Reanimated library and identify its advantages compared to other approaches.

Materials and Methods

In the study by Kuttig A. B. [1], the use of frameworks, including Reanimated, for creating animations is examined. The author focuses on aspects of performance optimization and the interaction of animations with other components. Methods for addressing issues that arise when working with applications containing numerous elements are explored.

The article by Boduch A., Derks R., and Sakhniuk M. [2] emphasizes the selection of tools for creating animations that ensure stable performance across various devices. An important aspect highlighted is the synchronization of animations with the application state, which facilitates the development of dynamic interfaces.

The work by Batista A. et al. [4] investigates methods for utilizing animations to enhance user experience in business applications. Although the study focuses on inventory management systems, the described approaches can be adapted for the React Native platform. Animations contribute to making interfaces more user-friendly, accelerating navigation, and improving responsiveness to user actions.

In the article by Taberham P. [5], animation is examined as a medium for artistic expression and as a tool for exploring the perception of multimedia forms. While this approach does not directly relate to React Native, it can inspire unconventional solutions in mobile application development.

Rubino V. S. [6] explores the technological and medical aspects of animation. The described approaches highlight the potential use of animation in fields such as medicine and engineering. These solutions are particularly valuable for professionals working with medical applications, where animation is crucial for data visualization and the creation of interactive tools. Articles like the work by Seo B. A. [3] propose combined approaches to cross-platform development but do not specifically address the unique aspects of working with animations.

Furthermore, scientific literature does not sufficiently address the performance of animations in large-scale applications. There is a lack of methods for creating multi-component animations using Reanimated in conjunction with state management tools such as Redux or MobX. Real-world application examples demonstrating improvements achieved through the use of Reanimated are also absent.

The methodology of this study involves theoretical analysis of documentation and testing the library in various projects.

Results and Discussion

Creating animations in React Native requires synchronizing numerous events and performing calculations in the JavaScript thread. Animations with intensive computations, such as parallax effects or gesture handling, can slow down application performance. Reanimated addresses this challenge through a two-tiered architecture, where animation calculations occur in the UI thread instead of the JavaScript thread. This approach eliminates delays caused by data transmission between threads, improving performance. Table 1 outlines the main elements of working with animation in React Native using the Reanimated library.

Table 1.

The main elements of working with animation in React Native using the Reanimated library [1, 4, 5]

Animation Work Element

Description

useSharedValue

Used for animations and synchronization with the native thread. These variables store values such as positions, scales, or angles, which are updated in real time.

useAnimatedStyle

Links shared values with CSS-like styles such as transform or opacity, allowing style changes based on animations.

withTiming

A function for creating animations using a timing function, enabling value changes over a set duration.

withSpring

Enables animations with natural transitions.

withDecay

Simulates inertia after user interactions, such as scrolling or swiping.

runOnJS

Executes JavaScript code on the main thread, enabling interaction with JavaScript logic during animations.

worklets

Processes animations and gestures with high performance, without delays.

useAnimatedGestureHandler

Synchronizes user gestures with animations and visual changes.

withDelay

Adds a delay before the animation starts.

cancelAnimation

Cancels the current animation, stopping it before completion.

useDerivedValue

Creates dependent animations, such as changing opacity based on scroll position or object placement.

 

The JavaScript thread manages business logic, while animations are handled in the native thread. This optimizes the use of mobile device resources, as operations involving coordinates or opacity are executed at the level of native components. As a result, response times are reduced, and reliance on JavaScript execution is minimized.

Reanimated provides two approaches for creating animations: declarative and imperative. The declarative approach is used for smooth state transitions, while more complex scenarios, such as gesture handling or managing multiple animations, require the imperative approach. This enables highly precise animation configurations. Implementing animations synchronized with user actions necessitates accurate handling of multiple gestures simultaneously. Reanimated effectively addresses this challenge, ensuring smooth animations even during interactions with numerous gestures [2, 3, 6]. Figure 1 illustrates the basic principles of working with animation in Reanimated.

 

Figure 1. Basic principles of working with animation in Reanimated [2, 3, 6].

 

Working with animations in Reanimated within React Native is based on the efficient use of native threads, worklets, and shared values. These principles enable the creation of high-performance, smooth animations and their integration with gestures, movements, and navigation, thereby enhancing the user experience. Reanimated provides flexible and powerful tools for creating animations but requires an understanding of working with native code, which makes it challenging for beginners but ideal for complex and high-performance interfaces. Below is an example of implementing a drag-and-drop animation using useAnimatedGestureHandler:

import { PanGestureHandler } from 'react-native-gesture-handler';

import { useAnimatedGestureHandler, useAnimatedStyle, withSpring } from 'react-native-reanimated';

 

const DragComponent = () => {

  const gestureHandler = useAnimatedGestureHandler({

    onStart: (_, context) => {

      context.offsetX = 0;

    },

    onActive: (event, context) => {

      context.offsetX = event.translationX;

    },

    onEnd: (_, context) => {

      context.offsetX = withSpring(0);

    },

  });

 

  const animatedStyle = useAnimatedStyle(() => ({

    transform: [{ translateX: context.offsetX }],

  }));

 

  return (

    <PanGestureHandler onGestureEvent={gestureHandler}>

      <Animated.View style={[styles.box, animatedStyle]} />

    </PanGestureHandler>

  );

};

 

In this example, drag-and-drop functionality is implemented with spring animation via withSpring, allowing smooth movement of the object across the screen and returning it to its original position after the gesture ends.

For synchronizing animations such as scrolling or scaling, Reanimated provides tools like withDelay, withSequence, and withRepeat. These functions enable control over the order, duration, and repetition of animations, ensuring harmonious interaction between effects.

The interpolate function is used to transform values, for example, changing animation parameters such as position, scale, or rotation. Additionally, the Easing function is applied to manage the animation curve, creating smooth transitions between states [1, 4]. An example is shown below:

const animatedValue = useSharedValue(0);

const animatedStyle = useAnimatedStyle(() => {

  return {

    opacity: interpolate(animatedValue.value, [0, 1], [0, 1]),

    transform: [

      { scale: interpolate(animatedValue.value, [0, 1], [0.5, 1]) }

    ]

  };

});

 

In turn, the division of computations between the JavaScript thread and the native thread improves interface performance and responsiveness. The library's functionality enables developers to create precise and dynamic animations, making it a significant tool in mobile application development. Below, Table 2 outlines the advantages and disadvantages of working with animation in React Native using the Reanimated library.

Table 2.

Advantages and disadvantages of working with animation in React Native using the Reanimated library (compiled by the author)

Advantages

Disadvantages

Reanimated operates at the native level, reducing the load on the main thread and ensuring smooth animations, even for complex or long-running animations.

Using Reanimated requires an understanding of its concepts, such as "worklets," "shared values," and the specifics of native execution.

Reanimated provides developers with full control over animations, including the ability to write custom animations with synchronization.

While Reanimated is actively evolving, its documentation is less detailed compared to other popular solutions, making it harder to learn.

The library enables the creation of complex animations, such as gesture-based animations, scrolling, and transformations.

Some third-party libraries are not compatible with Reanimated out of the box, requiring additional configuration for integration.

Reanimated uses native animations, making them smoother and more efficient compared to standard JavaScript-based solutions.

Since animations are executed in the native thread, debugging can be challenging and requires specific tools for working with native code.

Reanimated 2 includes support for advanced gestures, such as drag and pinch, with high performance. This is useful for creating interactive and dynamic interfaces.

Some Reanimated features may not work or require extra effort to function with outdated versions of React Native.

It introduces the ability to create complex animations that run at the native level and offers improved support for declarative syntax.

Reanimated may not easily integrate with other animation libraries or methods, such as the standard Animated API, which can create challenges in projects that use mixed approaches.

Reanimated allows developers to easily create animations dependent on variables and states and to build complex animation sequences.

Reanimated requires a properly configured environment with native dependencies, which can pose challenges in cross-platform projects.

The library can handle gestures, enabling the creation of animations based on user interactions with the interface.

For simple animations, Reanimated may be excessive; lightweight solutions such as the standard Animated API are preferable.

 

Thus, the process of working with animations in React Native using the Reanimated library involves a sequence of steps, starting with library integration, creating animation effects, managing animation states, and concluding with their implementation in the interface. It is important to understand how library components such as shared values and worklets interact and how animation functions influence the creation of visual effects.

Reanimated significantly improves performance, as most operations are executed directly on the UI thread through worklets. This eliminates the need for constant updates to components on the main thread, which is critical for smooth animations and a high frame rate.

Working with animations in Reanimated relies on the use of shared values to store data, the calculation of styles through useAnimatedStyle, and the management of changes using functions such as withSpring, withTiming, and others. Integration with gestures and the execution of animations directly on the UI thread make Reanimated a powerful tool for creating dynamic and high-performance animations in React Native.

Conclusion

The Reanimated library is a tool for animation development in React Native, ensuring improved performance and interface responsiveness during user interactions. This article explored its functional capabilities, principles of operation, and methods of integration into projects. Reanimated transfers animation calculations from the JavaScript engine to the native level, reducing delays and enhancing interface responsiveness during intensive animations and gesture interactions.

The use of Reanimated reduces the load on the main thread while ensuring the smoothness of visual effects. A key feature is its ability to customize animations, manage gestures, and create screen transitions—features that are not possible with the standard Animated library.

Integrating Reanimated into a project allows for the optimization of mobile application performance and enhancement of their visual components. The library provides tools for creating animations that function effectively under various conditions. The application of Reanimated significantly enhances the user experience.

 

References:

  1. Kuttig A. B. Professional React Native: Expert techniques and solutions for building high-quality, cross-platform, production-ready apps. – Packt Publishing Ltd, 2022.
  2. Boduch A., Derks R., Sakhniuk M. React and React Native: Build cross-platform JavaScript applications with native power for the web, desktop, and mobile. – Packt Publishing Ltd, 2022.
  3. Seo B. A Case Study of Combining Two Cross-platform Development Frameworks for Storybook Mobile App //KSII Transactions on Internet and Information Systems (TIIS). – 2023. – Т. 17. – №. 12. – С. 3345-3363.
  4. Batista A. et al. Mobile design based on UX/UI to improve the poor experience of business owners in inventory stock management //2023 VI Congreso Internacional en Inteligencia Ambiental, Ingeniería de Software y Salud Electrónica y Móvil (AmITIC). – IEEE, 2023. – С. 1-4.
  5. Taberham P. Music Visualization and Medium Expansion: Key Themes in Experimental Animation //A Companion to Experimental Cinema. – 2022. – С. 210-229.
  6. Horisaki-Christens N. Video as World Mandala: The Role of Nakajima Kō’s Animaker and Aniputer in Defining a Cosmic Vision of Video //Leonardo. – 2024. – Т. 57. – №. 6. – С. 635-642.
  7. Rubino V. S. Reanimation Through Electro-Stimulation //The Rail, the Body and the Pen: Essays on Travel, Medicine and Technology in 19th Century British Literature. – 2021. – С. 135.
Информация об авторах
Журнал зарегистрирован Федеральной службой по надзору в сфере связи, информационных технологий и массовых коммуникаций (Роскомнадзор), регистрационный номер ЭЛ №ФС77-54434 от 17.06.2013
Учредитель журнала - ООО «МЦНО»
Главный редактор - Звездина Марина Юрьевна.
Top