React native reanimated worklet

React native reanimated worklet

Introduction to worklet in react native reanimated.

What is reanimated ?

Reanimated is an animation library that allows you to run animation entirely on UI thread. In this article we are mainly going to focus on ‘react-native-reanimated’ version 2. Which introduces worklet.

Worklets

It is simple javascript function. that can be handled entirely on the UI thread. We define worklet just by adding worklet keyword.

  const sum = (a:number,b:number) => {
    return a+b;  
  }

  const sumWithWorklet = (a:number,b:number) => {
    "worklet"
    return a + b;
  }

In the above code you get to know how to define an worklet. Now Let's see some other properties of worklet.

  • Worklet can be called inside another worklet in sync
const sumTwoNumber = (a:number,b:number) => {
  'worklet'
  return a + b;
}

const getSum = (from) => {
  'worklet'
  console.log(sumTwoNumber(10,20));    // one worklet can be executed in another one.
 }
  • Worklet can use constants from main Javascript thread.

eg.


  const getOs = (from) => {
  'worklet'
  console.log(`You are on ${Platform.OS}`);  
 }
  • Worklet can also execute function from main Js thread but that can be executed in async.

eg.


const sayHelloFromJsThread = () => Alert.alert('I am getting executed from the worklet');


const workletFunction = () => {
  'worklet'
  sayHelloFromJsThread()
}

To execute the worklet getCurrentDate we need to get another function from react-native-reanimated called runOnUI. Here is an example.


const App = () => {
  return (
    <View>
      <Button onPress={() => runOnUI(sumTwoNumber)(10,20)}>RUN WORKLET</Button>
  </View>
  )
}

As you can see we run the function using runOnUI(sumTwoNumber)(10,20) here you can also pass arguments in sumTwoNumber like this runOnUI(getCurrentDate)('10,20'). Here we are passing 10,20 from main thread to UI thread.

This is all we have in worklet. In the later article i will also show you how to create some small animation using react-native-reanimated which can help us to get better understanding to use react native reanimated in our own react native application.

Did you find this article valuable?

Support adityakmr by becoming a sponsor. Any amount is appreciated!