Good practices
This page lists practices that minimize the multi-threading overhead when using Worklets APIs.
Re-use your runtimes
Create Worker Runtimes once, for example at app startup or in a module scope, and keep a reference to them.
Every call to createWorkletRuntime
creates a new JavaScript runtime. With the default queue, it also creates a new
thread to run it on.
While Hermes is a light-weight JavaScript engine, the performance impact of frequent Runtime creation and destruction can be noticeable, especially in development builds.
Make brand-new Runtimes when you need to be sure they come with a clean environment, without any previous work that could impact their state.
function processInBackground(data) {
const workerRuntime = createWorkletRuntime({ name: 'worker' });
scheduleOnRuntime(workerRuntime, processData, data);
}
const workerRuntime = createWorkletRuntime({ name: 'worker' });
function processData(data) {
'worklet';
// ...
}
function processInBackground(data) {
scheduleOnRuntime(workerRuntime, processData, data);
}
Don't call createWorkletRuntime inside a component body or inside a function
that runs often.
Re-use your worklet functions
Define worklet
functions once, at the
module level or with
useCallback, and pass the
same function to the threading functions every time.
The Worklets library caches the serialized copy of a worklet function by the identity of the function object. On the target Runtime, a serialized worklet function is turned into a JavaScript function once and then retained. When you pass the same function object again, both steps are skipped.
A new function object, for example an arrow function created on every call or every render, is serialized and turned into a function again. This is especially taxing when the function has a large closure.
function onPress(value) {
scheduleOnUI((value) => {
'worklet';
console.log(value);
}, value);
}
function logValue(value) {
'worklet';
console.log(value);
}
function onPress(value) {
scheduleOnUI(logValue, value);
}
Prefer arguments over closures
Pass values as arguments instead of capturing them in a closure. This is related to re-using your worklet functions: a worklet function whose closure changes has to be created anew, so it can't be re-used.
function Header({ title }) {
// A new worklet function with a new closure on every render.
function logTitle() {
'worklet';
console.log(title);
}
const onPress = () => scheduleOnUI(logTitle);
// ...
}
function logTitle(title) {
'worklet';
console.log(title);
}
function Header({ title }) {
const onPress = () => scheduleOnUI(logTitle, title);
// ...
}
Avoid wrapper worklet functions
Don't create worklet functions that only forward their closure to another
worklet function. Pass the arguments to the threading function directly. In
both examples below, foo is a worklet function:
function foo(arg1, arg2) {
'worklet';
// code...
}
function schedule(arg1, arg2) {
// A new worklet function with a new closure including `arg1` and `arg2`
// on every call.
scheduleOnUI(() => {
'worklet';
foo(arg1, arg2);
});
}
function schedule(arg1, arg2) {
scheduleOnUI(foo, arg1, arg2);
}
Transfer granular objects
Pass or capture only the values that a worklet function needs, not the whole object that contains them.
When a worklet function uses a property of an object from its closure, the Worklets library copies the whole object, with all its nested values, and not only the property that you access. In development builds, it also makes the original object immutable after the copy. See Tried to modify key of an object which has been converted to a serializable for details.
const obj = { propAccessedInWorklet: 1, propNotAccessedInWorklet: 2 };
function worklet() {
'worklet';
console.log(obj.propAccessedInWorklet);
}
scheduleOnUI(worklet);
const obj = { propAccessedInWorklet: 1, propNotAccessedInWorklet: 2 };
function worklet(propAccessedInWorklet) {
'worklet';
console.log(propAccessedInWorklet);
}
scheduleOnUI(worklet, obj.propAccessedInWorklet);
The property is read when you call scheduleOnUI, so the worklet function
always gets its current value.
Use the target Runtime's event loop
When a worklet function has to run repeatedly or after a delay, schedule it with the event loop of the runtime where it runs, not from the React Native Runtime.
Worker Runtimes created with the default
enableEventLoop
option provide setTimeout, setInterval, setImmediate,
requestAnimationFrame and queueMicrotask. The UI
Runtime provides timers too, driven by
the frames of the native rendering layer. See Using the event
loop.
If you call scheduleOnRuntime from a
timer on the React Native Runtime instead, every tick waits for the JavaScript
thread and sends a new job to the target runtime.
In both examples below, tick is a worklet function:
function tick() {
'worklet';
// ...
}
setInterval(() => {
scheduleOnRuntime(workerRuntime, tick);
}, 100);
scheduleOnRuntime(workerRuntime, () => {
'worklet';
const intervalId = setInterval(tick, 100);
// Call clearInterval(intervalId) on the Worker Runtime
// when the work is complete.
});
For repeating timers, keep the id that setInterval returns and call
clearInterval with it on the same Runtime when the work is complete.
Prefer async invocations
Whenever you need to return a value from a worklet function, prefer to do it
with asynchronous APIs, such as runOnUIAsync
and runOnRuntimeAsync, to avoid
pre-emption costs. Synchronous APIs, such as
runOnUISync and
runOnRuntimeSync, block the calling
thread until the target Runtime finishes the worklet function. This is
especially important when dealing with the UI Runtime. You can read more about
it in the Returning results tutorial and
in Running worklet functions on the UI
Runtime.
In both examples below, measureLayout is a worklet function that returns a
value:
function measureLayout() {
'worklet';
// ...
return layout;
}
function onPress() {
const layout = runOnUISync(measureLayout);
console.log(layout);
}
async function onPress() {
const layout = await runOnUIAsync(measureLayout);
console.log(layout);
}