Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 71 ยท Animation and Gestures

Reanimated and Gesture Handler

Build fluid UI-thread animations in React Native with Reanimated shared values and worklets, and combine gestures with Gesture Handler, including swipe-to-dismiss.

The built-in Animated API covers fades, slides and simple springs. But some interfaces need more: a card that follows your finger exactly, flicks away when you swipe fast, and snaps back when you let go slowly. That requires reading touch positions many times per second and updating the view in the same frame. If that conversation has to cross to the JavaScript thread and back, it feels laggy.

Two libraries solve this together. React Native Reanimated runs animation code on the UI thread, and React Native Gesture Handler recognizes touches natively and hands the result to Reanimated without a round trip through JavaScript. In this lesson you learn shared values, worklets, animated styles, gesture composition, and the full swipe-to-dismiss recipe.

Read-only and stand-in. Reanimated needs a native build and a Babel plugin, and gestures need real touch input, so the library code is shown in plain blocks. The TryIts run stand-ins: a timeline that shows why UI-thread animation survives a busy JavaScript thread, and the decision logic and easing math behind swipe-to-dismiss. Setup details differ between Reanimated versions, so follow the install guide for the version you use. The API shown here is the stable core.

Why a second animation library

With Animated and the native driver you describe an animation ahead of time and the native side runs it. That is great for fixed motion, but you cannot run your own code per frame: reacting to a finger, computing a value from two others, or branching on velocity still needs JavaScript.

Reanimated lets you write small functions that run on the UI thread itself. These functions are called worklets. Because they execute where the views live, they can read a touch position and move a view in the same frame, even if the JavaScript thread is busy rendering a big list.

Two threads, one smooth frame

JS thread Your components, state and logic.
UI thread Draws views, handles touches.

Worklets move small functions to the UI thread.

1 / 2

Shared values and animated styles

A shared value is Reanimated's version of state that lives on the UI thread. You read and write it through .value. Writing it does not re-render your component.

TSX
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  withTiming,
} from 'react-native-reanimated';
import { Button, View } from 'react-native';

export default function Box() {
  const offset = useSharedValue(0);

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: offset.value }],
  }));

  return (
    <View>
      <Animated.View
        style={[{ width: 80, height: 80, backgroundColor: 'steelblue' }, animatedStyle]}
      />
      <Button title="Slide" onPress={() => (offset.value = withSpring(offset.value + 100))} />
      <Button title="Reset" onPress={() => (offset.value = withTiming(0, { duration: 250 }))} />
    </View>
  );
}

Read it line by line.

  • useSharedValue(0) creates the value once, like a ref.
  • useAnimatedStyle takes a function that returns style properties. Reanimated re-runs it whenever a shared value it reads changes, and the function itself runs on the UI thread.
  • withSpring(target) and withTiming(target, config) are not functions that animate immediately: they are descriptions you assign to .value, and Reanimated runs them from there. You can also use withDecay for momentum after a fling, and combine them with withSequence, withDelay and withRepeat.

Reanimated also has its own interpolate helper that works like the one in Animations with the Animated API, and useDerivedValue to compute one shared value from others.

Worklets

A worklet is a function marked with the 'worklet' directive on its first line. The Babel plugin finds it and copies it to the UI thread together with the values it uses.

TSX
function clamp(value: number, min: number, max: number) {
  'worklet';
  return Math.min(Math.max(value, min), max);
}

You rarely write that directive yourself, because callbacks passed to useAnimatedStyle, gesture handlers and the with... animations are turned into worklets automatically. What you must remember are the rules of the UI thread:

  • A worklet captures a copy of the values it uses, not a live link to your component's variables.
  • Calling a regular JavaScript function from a worklet is not allowed, because that function lives on the other thread.
  • To call back into JavaScript (to update React state, navigate, or call an API), use runOnJS: runOnJS(setDone)(true). Note the double call: the first wraps the function, the second calls it with arguments. Newer releases of the worklets runtime add an equivalently named helper, so check the notes of your version.

Gesture Handler

Gesture Handler replaces React Native's built-in touch system with a native gesture recognizer, which is why gestures stay reliable on a busy JavaScript thread. You describe gestures with a builder and attach them with GestureDetector.

TSX
import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler';

// Once, near the root of the app:
export default function App() {
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      {/* the rest of the app */}
    </GestureHandlerRootView>
  );
}

The root view is required, otherwise gestures do not work on Android. Individual gestures are small builders:

TSX
const pan = Gesture.Pan()
  .onBegin(() => { isPressed.value = true; })
  .onUpdate((event) => { x.value = event.translationX; })
  .onFinalize(() => { isPressed.value = false; });

const doubleTap = Gesture.Tap()
  .numberOfTaps(2)
  .onEnd(() => { scale.value = withSpring(scale.value * 1.5); });

Callbacks such as onUpdate receive an event with fields like translationX, translationY and velocityX, and, when Reanimated is installed, they run as worklets on the UI thread by default. That is exactly where you want to write a shared value.

Composing gestures

Real interfaces use several gestures on the same view. Three helpers say how they relate:

Helper Meaning Example
Gesture.Simultaneous(a, b) Both can be active at once Pinch and rotate an image together
Gesture.Exclusive(a, b) a wins; b only if a fails Double tap to zoom, single tap to select
Gesture.Race(a, b) The first to activate wins; the others are cancelled Pan or long press, whichever starts first
TSX
const zoomAndRotate = Gesture.Simultaneous(pinch, rotation);
const tapRules = Gesture.Exclusive(doubleTap, singleTap);

<GestureDetector gesture={zoomAndRotate}>
  <Animated.View style={animatedStyle} />
</GestureDetector>;

With Exclusive, the single tap waits briefly to be sure the user is not about to tap twice, so give it the lower priority by listing it last.

Recipe: swipe to dismiss

A list row follows your finger horizontally. If you drag it far enough, or flick it quickly, it flies off screen and the row is removed. Otherwise it springs back.

TSX
import { Dimensions } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, {
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withSpring,
  withTiming,
} from 'react-native-reanimated';

const { width } = Dimensions.get('window');
const DISTANCE = width * 0.35;
const FLICK_SPEED = 800; // pixels per second

export function SwipeRow({ children, onDismiss }: { children: React.ReactNode; onDismiss: () => void }) {
  const x = useSharedValue(0);

  const pan = Gesture.Pan()
    .activeOffsetX([-10, 10]) // start only after a clear horizontal move
    .onUpdate((event) => {
      x.value = event.translationX;
    })
    .onEnd((event) => {
      const farEnough = Math.abs(event.translationX) > DISTANCE;
      const fastEnough = Math.abs(event.velocityX) > FLICK_SPEED;

      if (farEnough || fastEnough) {
        const direction = event.translationX > 0 ? 1 : -1;
        x.value = withTiming(direction * width, { duration: 200 }, (finished) => {
          if (finished) runOnJS(onDismiss)();
        });
      } else {
        x.value = withSpring(0);
      }
    });

  const rowStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: x.value }],
    opacity: 1 - Math.min(Math.abs(x.value) / width, 1) * 0.6,
  }));

  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={rowStyle}>{children}</Animated.View>
    </GestureDetector>
  );
}

Four decisions make it feel right. activeOffsetX stops the pan from stealing vertical scrolls in a list. The row follows the finger one-to-one in onUpdate. onEnd decides by distance or speed, because a short fast flick means "get rid of it" even if it did not travel far. And the completion callback of withTiming uses runOnJS to tell React to remove the item, only once the exit animation finished.

Stand-in: why the UI thread keeps moving

This TryIt compares two animations of the same 300-pixel slide. In one, each frame is computed by JavaScript, and the JavaScript thread is busy between 300 and 700 ms. In the other, the animation runs on the UI thread. The timeline is simulated with fixed numbers, so it is the same on every run.

A busy JS thread: JS-driven versus UI-thread animation

This is the entire argument for worklets and for the native driver in one picture: work that must stay smooth should not depend on a thread that your app also uses for everything else.

Stand-in: the swipe decision and its easing

The second TryIt reproduces the onEnd logic from the recipe as a pure function, runs it for several fake gestures, and samples the ease-out curve that withTiming would use for the exit. Easing functions are just maps from time progress to value progress.

Swipe-to-dismiss decisions and exit easing

Notice how the ease-out exit covers most of the distance in the first 100 ms and then slows: the card leaves quickly and gently. Keeping the decision in a pure function like decide is also what makes this logic testable without a device (see Testing React Native Apps).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a worklet?

    Worklets are small functions marked (explicitly or automatically) so the Babel plugin can run them on the UI thread, where the views live.
  2. 2. You need to update React state when a withTiming exit animation finishes. What do you use inside the worklet callback?

    State setters live on the JavaScript thread. runOnJS hops from the UI-thread worklet back to JavaScript to call them.
  3. 3. Which composition helper means 'double tap wins; single tap only if the double tap fails'?

    Exclusive gives priority in the order listed: the first gesture gets a chance, and the next one only activates if the first fails.
  4. 4. Why does the swipe recipe check velocity as well as distance?

    Users flick quickly when they mean 'throw this away', even if the finger did not travel far. Combining distance and speed matches that intent.
  5. 5. What does writing to a shared value do to your React component?

    Shared values are outside React's render cycle. Only the animated styles and derived values that read them update.

Summary

  • Reanimated runs animation code on the UI thread, so motion stays smooth when JavaScript is busy.
  • A shared value is read and written with .value; useAnimatedStyle turns shared values into styles without re-rendering.
  • withTiming, withSpring and withDecay are animations you assign to a shared value; worklets are functions copied to the UI thread, and runOnJS calls back into JavaScript.
  • Gesture Handler recognizes touches natively. Wrap the app in GestureHandlerRootView and attach gestures with GestureDetector.
  • Combine gestures with Simultaneous, Exclusive and Race.
  • Swipe-to-dismiss follows the finger, then decides by distance or velocity: animate off screen, or spring back.

Next, learn how to prove all of this works in Testing React Native Apps.