Understanding runOnJS and runOnUI in React Native Reanimated

When building React Native applications with gesture-based interactions, it's essential to manage side effects such as calling JavaScript functions or updating the UI from within the gesture handlers. React Native Reanimated provides two functions, runOnJS and runOnUI, to handle these scenarios effectively. Let's explore each of them in detail:

runOnJS

runOnJS is a function provided by React Native Reanimated that allows you to call JavaScript functions asynchronously from within the gesture handlers. This function ensures that the JavaScript code runs on the JavaScript thread, separate from the UI thread, preventing any potential performance bottlenecks or UI freezes.

Usage:

 const pan = Gesture.Pan()
        .onBegin(() => {
            pressed.value = true;
        })
        .onChange((event) => {
            offset.value = event.translationY;
        })
        .onFinalize((event) => {
            offset.value = withSpring(-120);
            pressed.value = false;
            runOnJS(throwCard)(info.card_no);
        })

Here, throwCard(cardInfo) is a function that emits message to web-socket server.

runOnUI

runOnUI is another function provided by React Native Reanimated, allowing you to update the UI components from within the gesture handlers. Unlike runOnJS, runOnUI ensures that the UI updates occur on the UI thread, preventing any flickers or inconsistencies in the rendering.

Usage:

import { runOnUI } from 'react-native-reanimated';

// Example usage within a gesture handler
const panGestureHandler = Gesture.Pan()
  .onActive((event) => {
    runOnUI(updateUI)(event.translationX, event.translationY);
  });

Key Differences:

  • Thread Execution: runOnJS executes JavaScript functions on the JavaScript thread, while runOnUI performs UI updates on the UI thread.

  • Use Cases:

    • Use runOnJS for calling JavaScript functions that don't directly affect the UI, such as data manipulation or business logic.

    • Use runOnUI for updating UI components based on gesture events or other asynchronous operations.

Conclusion:

In conclusion, runOnJS and runOnUI are powerful tools provided by React Native Reanimated for managing side effects and updating the UI in gesture-based interactions. Understanding when and how to use these functions can significantly improve the performance and responsiveness of your React Native applications.

0
Subscribe to my newsletter

Read articles from Prakash Tajpuriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prakash Tajpuriya
Prakash Tajpuriya

Web Developer