How to ensure synchronization between JS rendering and UI animation threads? #6223
Replies: 1 comment
-
Hey! Answering your questions:
We cannot manually re-render components on the UI thread and trigger re-renders directly from the UI thread.
You cannot keep the JS and the UI thread in sync. In such a case, both threads will have to wait for each other on every change which will result in huge performance loss. In general, most of the time, you should communicate from the JS to the UI thread (on the JS thread, you create an animation, which is executed on the UJ thread). Questions from me:
|
Beta Was this translation helpful? Give feedback.
-
Apologies in advance if this is a commonly asked question. I was unable to pinpoint similar threads.
As an example, I have a carousel component where users can swipe through slides. Each slide’s position is controlled via the following
useAnimatedReaction
:This setup allows:
To handle slide changes triggered by user gestures, the current slide state is updated as follows (in a gesture handler):
This approach updates the state and triggers a re-render of the slides with their new indices on the JS thread.
Problem:
The main issue arises when the content within the slides is heavy, causing the JS thread FPS to drop. Consequently, it will take a little longer for the slideIndex in the useAnimatedReaction to update as React components re-render, causing the gesture/animation to behave erratically.
Current Workaround:
To mitigate this, I have been duplicating the relevant state into a sharedValue to ensure react-native-reanimated code reads from that. However, this feels like a temporary solution and I foresee similar discrepancies emerging in other areas.
Question:
How can I ensure that the animation/gesture state and the React render state remain in sync, especially in cases where the content is heavy and affects JS thread performance? Are there best practices or patterns that I should follow to avoid these synchronization issues in the long term?
Ideally we would have way of consistently triggering React re-renders on the UI thread. Does such a thing exist?
Beta Was this translation helpful? Give feedback.
All reactions