tezvyn:

What is a worklet in Reanimated

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

Reanimated's execution model.

OUTLINE

a worklet is a JS function marked to run on the UI thread runtime with a captured snapshot of its scope, enabling synchronous per-frame work.

WHAT THIS TESTS Whether you understand the mechanism, a worklet, that lets Reanimated run logic synchronously on the UI thread, and its constraints around captured scope and cross-thread calls.

A GOOD ANSWER COVERS A worklet is a small JavaScript function that Reanimated, via its Babel plugin, marks and prepares to run on a separate JavaScript runtime hosted on the UI thread. The plugin captures the variables the function references and serializes a snapshot so the worklet can access them on the other thread. Because it executes on the UI thread, a worklet can read shared values and compute style objects synchronously every frame without crossing the asynchronous bridge, which is the whole reason animations stay smooth under JS load. Hooks like useAnimatedStyle, useDerivedValue, useAnimatedScrollHandler, and gesture callbacks accept worklets, and you can also tag a standalone function as a worklet. To run regular JavaScript, such as updating React state or navigating, from inside a worklet you must wrap the call in runOnJS, which schedules it back on the JS thread.

COMMON WRONG ANSWERS Thinking a worklet has live access to JS-thread variables; it only sees a captured snapshot from when it was created. Believing you can freely call any JS function inside a worklet without runOnJS. Confusing worklets with web workers or native threads; the UI thread runtime is still JavaScript. Assuming all functions passed to Reanimated hooks are automatically worklets without the plugin.

LIKELY FOLLOW-UPS How does runOnJS work and when is runOnUI needed, what are the limits on captured values, how does the Babel plugin transform the code, and what is the cost of frequently crossing back to JS.

ONE CONCRETE EXAMPLE Inside useAnimatedStyle you write a function returning transform from a shared value; that body is a worklet running on the UI thread each frame. If on a gesture end you need to call navigation.goBack, you cannot call it directly inside the worklet; you wrap it as runOnJS(navigation.goBack)(), which hops the result back to the JS thread to perform navigation.

Read the original → docs.swmansion.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.