React Native Worklets

0.8.1 · active · verified Sun Apr 19

React Native Worklets is a fundamental library providing low-level multithreading capabilities for React Native applications. It enables JavaScript functions, known as 'worklets', to execute directly on the UI thread or other background threads, bypassing the JavaScript thread bottleneck. This is crucial for achieving smooth animations, gestures, and other performance-sensitive operations that might otherwise cause UI jank. The library is closely integrated with and often used as a core component of `react-native-reanimated`. The current stable version is 0.8.1, with releases often coinciding with major `react-native-reanimated` updates. A key differentiator is its `Shareable` memory type, introduced in v0.8.0, which allows for efficient and safe data sharing between threads. It focuses on raw performance and thread control, rather than high-level animation APIs, serving as a building block for more complex libraries.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a worklet and execute a computationally heavy task on the UI thread using `runOnUI`, then pass the result back to the JavaScript thread with `runOnJS` to update React state, preventing UI freezes.

import { runOnUI, runOnJS, makeWorklet } from 'react-native-worklets';
import React, { useEffect, useState } from 'react';
import { Text, View, Button, StyleSheet } from 'react-native';

const calculateHeavyValue = makeWorklet((input) => {
  'worklet';
  let sum = 0;
  for (let i = 0; i < 1_000_000_000; i++) {
    sum += Math.random() * input;
  }
  return sum;
});

function App() {
  const [result, setResult] = useState(0);
  const [loading, setLoading] = useState(false);

  const startCalculation = () => {
    setLoading(true);
    runOnUI(() => {
      console.log('Calculating on UI thread...');
      const heavyResult = calculateHeavyValue(10);
      runOnJS(setResult)(heavyResult);
      runOnJS(setLoading)(false);
      console.log('Calculation finished on UI thread.');
    })();
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Worklets Demo</Text>
      <Text style={styles.resultText}>Result: {result.toFixed(2)}</Text>
      <Button
        title={loading ? 'Calculating...' : 'Start Heavy Calculation'}
        onPress={startCalculation}
        disabled={loading}
      />
      {loading && <Text style={styles.loadingText}>Please wait...</Text>}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  resultText: {
    fontSize: 18,
    marginVertical: 10,
  },
  loadingText: {
    fontSize: 16,
    color: 'gray',
    marginTop: 10,
  },
});

export default App;

view raw JSON →