0Pricing
React Native Academy · Lesson

Worklets and Running Code on the UI Thread

Mark functions as worklets with the 'worklet' directive, understand why this bypasses the JS bridge, and write gesture handlers that update shared values directly.

What Is a Worklet?

A worklet is a JavaScript function that Reanimated runs on the UI thread instead of the JavaScript thread. Reanimated's Babel plugin detects functions marked with the 'worklet' directive string at the top of their body and transforms them at build time into a form that can be sent to and executed on the UI thread.

Worklets are the core mechanism that allows Reanimated to process gesture data and update animations frame-by-frame at 60fps without ever involving the JavaScript thread or the bridge. They are the key architectural innovation that separates Reanimated from the classic Animated API.

function clamp(value, min, max) {
  'worklet'; // directive marks this as a worklet
  return Math.min(Math.max(value, min), max);
}

// This function can now be called inside
// useAnimatedStyle, useAnimatedGestureHandler,
// and other Reanimated hooks

The 'worklet' Directive

The 'worklet' string literal at the top of a function body is a special directive — similar to 'use strict'. The Reanimated Babel plugin scans for it and transforms the function so it can be serialized and run on the UI thread. Without this directive, calling the function from a worklet context would silently execute on the JS thread, causing potential crashes or incorrect behavior.

Functions passed to Reanimated hooks like useAnimatedStyle are automatically treated as worklets even without the directive. Regular utility functions called FROM those hooks need the directive explicitly.

// Automatically a worklet — Reanimated knows:
const animatedStyle = useAnimatedStyle(() => {
  return { opacity: opacity.value };
});

// Utility function needs explicit directive:
function mapRange(value, inMin, inMax, outMin, outMax) {
  'worklet';
  return ((value - inMin) / (inMax - inMin)) * (outMax - outMin) + outMin;
}

All lessons in this course

  1. Installing Reanimated and Shared Values
  2. Worklets and Running Code on the UI Thread
  3. Pan and Swipe Gestures with Gesture Handler
  4. Pinch-to-Zoom and Rotation
← Back to React Native Academy