When should we use runOnUI and runOnJS?
Asked Answered
S

1

7

If I understand correctly the purpose of 'worklets' it to run the code on UI thread:

With Reanimated 2 we spawn a secondary JS context on the UI thread that then is able to run JavaScript functions.

Then why do we need runOnUI and when should we use it, if it is doing the same thing:

Enables executing worklet function on the UI thread. Note that UI execution is asynchronous from the caller’s perspective. When you pass arguments, they will be copied to the UI JS context.

Socher answered 6/4, 2022 at 11:8 Comment(0)
E
2

I asked a similar question on software-mansion's github discussion page.

Here is their fairly thorough response:

Reanimated's worklets are executed on the UI thread and not the JS one. You can use runOnJS and runOnUI to schedule execution of a function on a different thread than you currently are, i.e. you should use runOnUI on the JS thread when you want some code to execute on the UI thread and similarly, you should use runOnJS on the UI thread when you want some code to execute on the JS thread. Keep in mind that only worklets can be executed on the UI thread, that's why you need to use runOnJS when changing state.

As a sidenote, if you don't want the callbacks of a gesture running on the UI thread, you can use .runOnJS(true) modifier, i.e.:

const pan = Gesture.Pan().runOnJS(true);

Elamite answered 26/10, 2022 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.