Usage
Running third party libraries in Worklets
Third party libraries have to be on an allow-list to use them in worklets. This is because libraries can come with side-effects that would break a Worklet Runtime. For instance, a library that imports something from React Native can't be used on a Worklet Runtime. This would load a second instance of React Native and break your app.
To add a library to the allow-list you only need to set importForwarding.moduleNames in the Worklet Syntax Babel plugin options. It's an array of library names. For instance, if you want to use my-library on a Worklet Runtime.
/** @type {import('react-native-worklets/plugin').PluginOptions} */
const workletsPluginOptions = {
importForwarding: { moduleNames: ['my-library'] },
};
The importForwarding API is temporary and will be replaced with a more robust solution in the future.
Running network requests in Worklets
Worklet Runtimes come with a standalone networking module. It's installed on every Worklet Runtime that has the event loop enabled, unless you opt out with enableNetworking: false.
const runtime = createWorkletRuntime({ name: 'worker' });
scheduleOnRuntime(runtime, async () => {
'worklet';
const response = await fetch('https://swmansion.com');
console.log(response.status);
});
| API | Supported |
|---|---|
fetch, Headers, Request, Response | ✅ |
XMLHttpRequest | ✅ |
Blob, FileReader | ✅ |
AbortController, AbortSignal | ✅ |
FormData | String fields only, encoded as multipart/form-data. |
| Response streaming | ❌ |
WebSocket | ✅ |
Requests share the app's cookie storage and TLS configuration. On Android, WebSocket also respects the system proxy settings and the app's cleartext traffic policy. React Native networking customizations, such as certificate pinning or interceptors, do not apply to WebSocket.
WebSocket follows the WHATWG interface and supports text, binary data, event listeners and subprotocols. Host names must be plain ASCII: internationalized host names, in Unicode or in their xn-- form, throw a SyntaxError.
Loading lazy chunks in Worklets
In development, Metro splits code behind import() into lazy chunks. A worklet function can import() such a module too: the Worklet Runtime fetches the chunk from Metro and evaluates it, like the RN Runtime does. The chunk is fetched with the runtime's own fetch, so the Worklet Runtime needs the networking API enabled. It is on by default. On a runtime created with enableNetworking: false, the import() rejects unless an initializer installs a fetch of its own on that runtime.
scheduleOnUI(async () => {
'worklet';
const { heavyComputation } = await import('./heavyComputation');
console.log(heavyComputation());
});
Reference
To see how the setup looks in a real project, you can check out the Bundle Mode Showcase App repository.