Nâng CaoReact Native iconReact Native

`useSharedValue` / `useAnimatedStyle` — chạy trên UI thread thế nào?

Worklet = block JS code được compile thành standalone function chạy trên UI thread, không cần roundtrip về JS thread.

useSharedValue(initial) tạo object có .value → đọc/ghi từ cả JS thread và UI thread. Internal là object C++ shared memory.

useAnimatedStyle(() => {...}, deps) marker 'worklet' ngầm — function callback được transform thành worklet bởi react-native-reanimated/plugin (Babel plugin). Mỗi frame UI thread gọi worklet → style mới → áp lên Fabric ShadowTree → render.

tsx
const progress = useSharedValue(0)

// Worklet — chạy UI thread, đọc shared value sync
const style = useAnimatedStyle(() => {
  return {
    opacity: progress.value,
    transform: [{ scale: 1 + progress.value * 0.5 }],
  }
})

// JS thread set value → trigger worklet rerun on UI thread
progress.value = withSpring(1)

Why fast:
- Không bridge serialize.
- Không chờ JS thread rảnh.
- 60–120 FPS guaranteed dù JS thread đang busy parse JSON 100MB.

Pitfall:
- Worklet không access được variable bên ngoài trừ khi capture qua dependency array — closure không hoạt động như JS thường.
- Console.log bên trong worklet không hiện trong JS console (UI thread riêng) — dùng runOnJS(console.log)(value) để log.
- Babel plugin react-native-reanimated/plugin phải là plugin cuối trong babel.config.js.

Xem toàn bộ React Native cùng filter theo level & chủ đề con.

Mở danh sách React Native