From 81c5b772246bfcbf095474553c2e6d30d382d301 Mon Sep 17 00:00:00 2001 From: Andre Pimenta Date: Fri, 1 Aug 2025 14:31:51 +0100 Subject: [PATCH 1/5] feat: Implement RN Worklets/Background Threads (#17674) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## **Description** This PR implements [Worklets](https://github.com/margelo/react-native-worklets-core). Worklets are small JavaScript functions that can be executed on a separate JavaScript Thread so they don't clog the main JS Thread. Perfect for heavy computations and processing. ## **Screenshots/Recordings** ### **Before** https://github.com/user-attachments/assets/ba3be2b7-71b8-4840-8a22-5407fa54a088 ### **After** https://github.com/user-attachments/assets/500036ce-252d-48d9-8148-4672618567bf ## **How to use RN Worklets (Threads)** # runAsync Purpose: runAsync is used to execute code on a different thread without blocking the main JS thread. When to use: Use it to offload functions to a background thread. Example: ``` import { Worklets } from 'react-native-worklets-core'; ... const fibonacci = (num: number): number => { 'worklet' if (num <= 1) return num; let prev = 0, curr = 1; for (let i = 2; i <= num; i++) { let next = prev + curr; prev = curr; curr = next; } return curr; } const context = Worklets.defaultContext const result = await context.runAsync(() => { 'worklet' return fibonacci(50) }) console.log(`Fibonacci of 50 is ${result}`) ``` # runOnJS Purpose: runOnJS is used to call a JavaScript function from within a worklet. Since worklets run on a separate thread, they cannot directly call JavaScript functions. runOnJS bridges this gap by allowing you to invoke JavaScript functions on the JavaScript thread. When to use: Use it when you need to communicate from the worklet thread back to the JavaScript thread. Example: ``` import { runOnJS } from 'react-native-worklets-core'; ... const [age, setAge] = useState(30) function something() { 'worklet' Worklets.runOnJS(() => setAge(50)) } ``` # useWorklet Purpose: useWorklet is a hook that allows you to define a worklet function directly within your React component. It ensures that the function is properly marked as a worklet and can run on the worklet thread. When to use: Use this hook when you need to define a function that will execute on the worklet thread. Example: ``` import { useWorklet } from 'react-native-worklets-core'; function MyComponent() { const myWorklet = useWorklet(() => { 'worklet'; console.log('This is running on the worklet thread'); }, []); return (