Mobile development · Intermediate · 28 min
Animate React Native screens with Reanimated 4
By Padding · Updated 18 Nov 2026
Expo SDK 58 · React Native 0.88 · Reanimated 4.7.1 · Gesture Handler 3.3 · Node.js 26 (node:26)
You will have a clinic queue screen in an Expo SDK 58 app that animates on the UI thread with Reanimated 4, with a timed progress bar, spring press feedback, a CSS-style transition and keyframe pulse, rows that animate in and out, swipe to cancel and a reduce-motion fallback, all proven by Jest tests.
On this page
Every animation in a React Native app has to be worked out frame by frame, 60 or more times a second. If the JavaScript thread does that work, the animation shares the thread with everything else your app does: rendering lists, parsing a network response, running a state update. When that thread is busy for 50 milliseconds, the animation misses three frames and the person sees a jump. On a budget Android phone, where the JavaScript thread is slower to begin with, that happens often.
Reanimated moves the per-frame work to the UI thread, the native thread that draws the screen. You describe the animation once in JavaScript; small functions called worklets then run on the UI thread and keep it moving, whatever the JavaScript thread is doing. Reanimated 4 runs only on React Native's New Architecture, which every Expo SDK 58 app uses, and its worklets now live in a separate package, react-native-worklets.
You will build one screen, a clinic's queue for the day, and animate it in six different ways: a timed progress bar, a spring on a button, a CSS-style transition, a looping keyframe animation, rows that animate in and out, and a row you can swipe away. Each piece has a Jest test that advances fake timers and checks the animated values, and the last step puts the screen on a phone.
Step 1 · Create the app and set up Jest for Reanimated
Create a throwaway app. When it asks to download create-expo-app, answer y:
cd ~
npx create-expo-app@5.0.0 reanimated-queue-demo
cd ~/reanimated-queue-demo
npm ls react-native-reanimated react-native-worklets react-native-gesture-handlerThe default template already installs Reanimated, Worklets and Gesture Handler at the versions SDK 58 was tested with: react-native-reanimated@4.7.1, react-native-worklets@0.13.0 and react-native-gesture-handler@3.3.x. Keep those. Reanimated 4.8 is out, but Expo Go ships with the native half of 4.7, and the JavaScript and native halves must match. If you start from an app without them, add them with npx expo install react-native-reanimated react-native-worklets react-native-gesture-handler. There is no babel.config.js to edit: Expo's Babel preset adds the worklets plugin when the package is installed.
Now add Jest, the Expo preset and React Native Testing Library:
cd ~/reanimated-queue-demo
npx expo install --dev jest-expo jest @types/jest
npm install --save-dev @testing-library/react-native@14.1.0 test-renderer@1.3.1Reanimated needs two things under Jest. Its resolver swaps in the web build of Reanimated and Worklets, which runs animations on timers instead of a UI thread, and setUpTests() hooks those timers up to Jest's fake clock and adds the toHaveAnimatedStyle matcher. Gesture Handler ships its own setup file that replaces its native module. One more line covers a gap between the two packages: Gesture Handler 3.3 asks Worklets for its UI runtime, which the web build of Worklets does not have, so the setup returns an empty stand-in.
cd ~/reanimated-queue-demo
cat > jest.setup.js <<'JS'
// Replaces Gesture Handler's native module with mocks.
require('react-native-gesture-handler/jestSetup')
// Drives Reanimated animations from Jest's (fake) timers and adds toHaveAnimatedStyle.
require('react-native-reanimated').setUpTests()
// Gesture Handler asks Worklets for a UI runtime, which the web build does not have.
jest.mock('react-native-worklets', () => ({
...jest.requireActual('react-native-worklets'),
getUIRuntimeHolder: () => ({}),
}))
JS
cat > jest.config.js <<'JS'
module.exports = {
preset: 'jest-expo',
// Loads the web builds of Reanimated and Worklets, which run without a UI thread.
resolver: 'react-native-reanimated/jest/resolver',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}
JS
npm pkg set scripts.test=jestCheck it worked
npm ls prints react-native-reanimated@4.7.1, react-native-worklets@0.13.0 and react-native-gesture-handler@3.3. followed by a patch number. Then confirm the config loads:
cd ~/reanimated-queue-demo
node -e "const c = require('./jest.config.js'); console.log(c.preset, c.resolver)"It prints jest-expo react-native-reanimated/jest/resolver.
Step 2 · Fill a progress bar with a shared value and withTiming
Start with the data: today's appointments, split into morning and afternoon, with names from several languages so you can see how longer names sit in a row.
cd ~/reanimated-queue-demo
mkdir -p src/queue
cat > src/queue/appointments.ts <<'TS'
export type Appointment = {
id: string
name: string
time: string
reason: string
}
export type Period = 'morning' | 'afternoon'
export const TODAY: Record<Period, Appointment[]> = {
morning: [
{ id: 'a1', name: 'Adaeze Okonkwo', time: '09:00', reason: 'Check-up' },
{ id: 'a2', name: 'Kwame Mensah', time: '09:30', reason: 'Blood test' },
{ id: 'a3', name: 'Wanjiru Kamau', time: '10:15', reason: 'Vaccination' },
],
afternoon: [
{ id: 'p1', name: 'Oluwaseun Ògúnlẹ̀yẹ', time: '14:00', reason: 'Follow-up' },
{ id: 'p2', name: 'Fatou Diallo', time: '14:45', reason: 'Physiotherapy' },
{ id: 'p3', name: 'Tomás García', time: '15:30', reason: 'Dressing change' },
],
}
export function makeWalkIn(n: number): Appointment {
return { id: `w${n}`, name: `Walk-in ${n}`, time: 'Now', reason: 'Walk-in' }
}
TSThe first animation is a bar showing how many patients have been seen. Three Reanimated pieces make it work:
useSharedValue(0)holds a number that both threads can read. Changing.valuefrom JavaScript does not re-render the component.withTiming(target, config)tells Reanimated to move the shared value totargetover a set time, on the UI thread.useAnimatedStyleis a worklet that turns the shared value into a style. Reanimated reruns it on the UI thread on every frame the value changes and applies the result to the view without going through React.
cd ~/reanimated-queue-demo
cat > src/queue/day-progress.tsx <<'TSX'
import { useEffect } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated'
type Props = { seen: number; total: number }
export function DayProgress({ seen, total }: Props) {
// 0 = nobody seen, 1 = everyone seen.
const progress = useSharedValue(0)
useEffect(() => {
const share = total === 0 ? 0 : seen / total
// Starts from wherever the bar is now, so a change mid-animation never jumps.
progress.value = withTiming(share, { duration: 400, easing: Easing.out(Easing.cubic) })
}, [seen, total, progress])
// Runs on the UI thread on every frame that progress changes.
const fillStyle = useAnimatedStyle(() => ({ width: `${progress.value * 100}%` }))
return (
<View
accessible
accessibilityRole="progressbar"
accessibilityLabel="Patients seen today"
accessibilityValue={{ min: 0, max: total, now: seen }}
style={styles.wrapper}
>
<Text style={styles.label}>
{seen} of {total} seen
</Text>
<View style={styles.track}>
<Animated.View testID="day-progress-fill" style={[styles.fill, fillStyle]} />
</View>
</View>
)
}
const styles = StyleSheet.create({
wrapper: { gap: 6, paddingHorizontal: 16, paddingVertical: 12 },
label: { fontSize: 14, color: '#2a2d33' },
track: { height: 8, borderRadius: 4, backgroundColor: '#d9dce1', overflow: 'hidden' },
fill: { height: 8, borderRadius: 4, backgroundColor: '#0b0c0e' },
})
TSXAnimated.View comes from Reanimated, not React Native. Only Reanimated's animated components accept the styles that useAnimatedStyle returns. Easing.out(Easing.cubic) starts fast and settles gently, which suits a value that has just changed; the default is Easing.inOut(Easing.quad) over 300 milliseconds.
Test it with Jest's fake timers. getAnimatedStyle reads the style Reanimated last applied, so you can check the bar part-way through and at the end:
cd ~/reanimated-queue-demo
cat > src/queue/day-progress.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { getAnimatedStyle } from 'react-native-reanimated'
import { DayProgress } from './day-progress'
beforeEach(() => jest.useFakeTimers())
afterEach(() => jest.useRealTimers())
function fillWidth(): number {
return parseFloat(String(getAnimatedStyle(screen.getByTestId('day-progress-fill')).width))
}
test('the bar fills from empty to the share of patients seen', async () => {
await render(<DayProgress seen={2} total={8} />)
expect(fillWidth()).toBe(0)
jest.advanceTimersByTime(100)
const early = fillWidth()
expect(early).toBeGreaterThan(0)
expect(early).toBeLessThan(25)
jest.advanceTimersByTime(400)
expect(fillWidth()).toBeCloseTo(25)
})
test('a new count animates on from where the bar already is', async () => {
const view = await render(<DayProgress seen={2} total={8} />)
jest.advanceTimersByTime(500)
await view.rerender(<DayProgress seen={6} total={8} />)
jest.advanceTimersByTime(500)
expect(fillWidth()).toBeCloseTo(75)
expect(screen.getByText('6 of 8 seen')).toBeOnTheScreen()
})
TSX
npx jest src/queue/day-progress --ciCheck it worked
Jest reports Tests: 2 passed, 2 total. The first test shows the bar part-way at 100 milliseconds, somewhere between 0 and 25 per cent, and at exactly 25 per cent once the 400 millisecond animation is over.
Step 3 · Give a button spring feedback with withSpring
A press that visibly responds within a frame feels solid, even when the work behind it takes longer. withSpring suits this better than a timed animation: it has no fixed duration, so if the finger lifts half-way through the press-in, the spring turns round from where it is.
cd ~/reanimated-queue-demo
cat > src/queue/call-next-button.tsx <<'TSX'
import { Pressable, StyleSheet, Text } from 'react-native'
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated'
// Stiff and well damped: a quick squeeze with no wobble.
const PRESS_SPRING = { damping: 20, stiffness: 400 }
type Props = { onPress: () => void; disabled?: boolean }
export function CallNextButton({ onPress, disabled = false }: Props) {
const scale = useSharedValue(1)
const style = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }))
return (
<Animated.View testID="call-next-scale" style={style}>
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled }}
disabled={disabled}
onPressIn={() => {
scale.value = withSpring(0.94, PRESS_SPRING)
}}
onPressOut={() => {
scale.value = withSpring(1, PRESS_SPRING)
}}
onPress={onPress}
style={[styles.button, disabled && styles.disabled]}
>
<Text style={styles.text}>Call next patient</Text>
</Pressable>
</Animated.View>
)
}
const styles = StyleSheet.create({
button: { minHeight: 48, borderRadius: 8, alignItems: 'center', justifyContent: 'center', backgroundColor: '#0b0c0e' },
disabled: { backgroundColor: '#9ba1ac' },
text: { fontSize: 16, fontWeight: '600', color: '#ffffff' },
})
TSXSetting scale.value inside onPressIn is ordinary JavaScript, so it runs on the JavaScript thread, but only once per press. From then on the spring runs frame by frame on the UI thread. The button keeps a minimum height of 48 points, a comfortable target for a thumb.
cd ~/reanimated-queue-demo
cat > src/queue/call-next-button.test.tsx <<'TSX'
import { fireEvent, render, screen } from '@testing-library/react-native'
import { getAnimatedStyle } from 'react-native-reanimated'
import { CallNextButton } from './call-next-button'
beforeEach(() => jest.useFakeTimers())
afterEach(() => jest.useRealTimers())
function scale(): number {
const { transform } = getAnimatedStyle(screen.getByTestId('call-next-scale')) as { transform: { scale: number }[] }
return transform[0].scale
}
test('the button squeezes while held and springs back on release', async () => {
const onPress = jest.fn()
await render(<CallNextButton onPress={onPress} />)
const button = screen.getByRole('button', { name: 'Call next patient' })
await fireEvent(button, 'pressIn')
jest.advanceTimersByTime(500)
expect(scale()).toBeCloseTo(0.94, 2)
await fireEvent(button, 'pressOut')
jest.advanceTimersByTime(500)
expect(scale()).toBeCloseTo(1, 2)
await fireEvent.press(button)
expect(onPress).toHaveBeenCalledTimes(1)
})
TSX
npx jest src/queue/call-next-button --ciCheck it worked
Jest reports Tests: 1 passed, 1 total: the scale settles at 0.94 while the button is held and back at 1 after release.
Step 4 · Use a CSS-style transition and a keyframe animation
Reanimated 4 adds a second way to animate, borrowed from CSS. Instead of shared values, you put transition... or animation... properties in an Animated.View's ordinary style, and Reanimated runs the animation on the UI thread for you. Use it for animations that follow state, where you would otherwise write a shared value, an effect and an animated style for one property.
The first is a Morning and Afternoon switch with an indicator that slides under the chosen option. When translateX changes, transitionProperty: 'transform' animates the change instead of jumping. Name the properties you want; the docs advise against 'all', which makes Reanimated watch every style property.
cd ~/reanimated-queue-demo
cat > src/queue/period-switch.tsx <<'TSX'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import Animated, { useReducedMotion } from 'react-native-reanimated'
import type { Period } from './appointments'
const SEGMENT_WIDTH = 140
const PERIODS: { key: Period; label: string }[] = [
{ key: 'morning', label: 'Morning' },
{ key: 'afternoon', label: 'Afternoon' },
]
// Kept as a plain function so a test can check it for both settings.
export function indicatorStyle(index: number, reduceMotion: boolean) {
return {
transform: [{ translateX: index * SEGMENT_WIDTH }],
transitionProperty: 'transform' as const,
transitionDuration: reduceMotion ? 0 : 250,
transitionTimingFunction: 'ease-out' as const,
}
}
type Props = { value: Period; onChange: (period: Period) => void }
export function PeriodSwitch({ value, onChange }: Props) {
const reduceMotion = useReducedMotion()
const index = PERIODS.findIndex((p) => p.key === value)
return (
<View style={styles.track} accessibilityRole="tablist">
<Animated.View testID="period-indicator" style={[styles.indicator, indicatorStyle(index, reduceMotion)]} />
{PERIODS.map((p) => (
<Pressable
key={p.key}
accessibilityRole="tab"
accessibilityState={{ selected: p.key === value }}
onPress={() => onChange(p.key)}
style={styles.segment}
>
<Text style={[styles.label, p.key === value && styles.selected]}>{p.label}</Text>
</Pressable>
))}
</View>
)
}
const styles = StyleSheet.create({
track: { flexDirection: 'row', alignSelf: 'center', width: SEGMENT_WIDTH * 2, borderRadius: 8, backgroundColor: '#f1f2f4' },
indicator: { position: 'absolute', top: 0, bottom: 0, width: SEGMENT_WIDTH, borderRadius: 8, backgroundColor: '#ffffff', borderWidth: 1, borderColor: '#d9dce1' },
segment: { width: SEGMENT_WIDTH, minHeight: 44, alignItems: 'center', justifyContent: 'center' },
label: { fontSize: 15, color: '#6a707b' },
selected: { color: '#0b0c0e', fontWeight: '600' },
})
TSXThe useReducedMotion line is there because people who turn on the system's reduce-motion setting should not get sliding and pulsing. Reanimated's animation functions already respect that setting; the CSS-style ones are not covered, so you set the duration to 0 yourself. Step 7 covers this in full.
The second is a keyframe animation: a small dot beside the next patient's name that pulses for as long as it is on screen. animationName takes a keyframes object, keyed by from, to or percentages, and animationIterationCount: 'infinite' keeps it looping. Define the keyframes outside the component, so the same object is used on every render.
cd ~/reanimated-queue-demo
cat > src/queue/next-badge.tsx <<'TSX'
import { StyleSheet, Text, View } from 'react-native'
import Animated, { type CSSAnimationKeyframes, useReducedMotion } from 'react-native-reanimated'
export const pulse: CSSAnimationKeyframes = {
from: { opacity: 1, transform: [{ scale: 1 }] },
'50%': { opacity: 0.35, transform: [{ scale: 0.8 }] },
to: { opacity: 1, transform: [{ scale: 1 }] },
}
export function pulseStyle(reduceMotion: boolean) {
if (reduceMotion) return {}
return {
animationName: pulse,
animationDuration: '1.2s',
animationIterationCount: 'infinite' as const,
animationTimingFunction: 'ease-in-out' as const,
}
}
export function NextBadge() {
const reduceMotion = useReducedMotion()
return (
<View style={styles.badge}>
<Animated.View style={[styles.dot, pulseStyle(reduceMotion)]} />
{/* The word carries the meaning; the pulse only draws the eye. */}
<Text style={styles.text}>Next</Text>
</View>
)
}
const styles = StyleSheet.create({
badge: { flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 8, paddingVertical: 2, borderRadius: 12, backgroundColor: '#f1f2f4' },
dot: { width: 8, height: 8, borderRadius: 4, backgroundColor: '#0b0c0e' },
text: { fontSize: 12, fontWeight: '600', color: '#2a2d33' },
})
TSXUnder Jest there is no UI thread to run the CSS engine, so a CSS transition shows its end state as soon as the style changes, and keyframe properties are not passed to the rendered view. Test what you can see: the end state after a press, and the two style functions.
cd ~/reanimated-queue-demo
cat > src/queue/period-switch.test.tsx <<'TSX'
import { fireEvent, render, screen } from '@testing-library/react-native'
import { useState } from 'react'
import type { Period } from './appointments'
import { pulse, pulseStyle } from './next-badge'
import { indicatorStyle, PeriodSwitch } from './period-switch'
function Harness() {
const [period, setPeriod] = useState<Period>('morning')
return <PeriodSwitch value={period} onChange={setPeriod} />
}
test('choosing Afternoon selects it and moves the indicator under it', async () => {
await render(<Harness />)
expect(screen.getByRole('tab', { name: 'Morning', selected: true })).toBeOnTheScreen()
await fireEvent.press(screen.getByRole('tab', { name: 'Afternoon' }))
expect(screen.getByRole('tab', { name: 'Afternoon', selected: true })).toBeOnTheScreen()
expect(screen.getByTestId('period-indicator')).toHaveStyle({ transform: [{ translateX: 140 }] })
})
test('the indicator transitions only its transform, and not at all with reduced motion', () => {
expect(indicatorStyle(1, false)).toMatchObject({ transitionProperty: 'transform', transitionDuration: 250 })
expect(indicatorStyle(1, true).transitionDuration).toBe(0)
})
test('the badge pulses forever unless motion is reduced', () => {
expect(pulseStyle(false)).toMatchObject({ animationName: pulse, animationIterationCount: 'infinite' })
expect(pulseStyle(true)).toEqual({})
})
TSX
npx jest src/queue/period-switch --ciCheck it worked
Jest reports Tests: 3 passed, 3 total. The indicator ends 140 points to the right, the width of one segment, once Afternoon is chosen.
Step 5 · Swipe a row to cancel with Gesture Handler
Now a row the receptionist can drag left to cancel an appointment. A gesture is where running on the UI thread matters most: the row must follow the finger on every frame, and a single late frame feels like the app has stuck.
Gesture Handler 3 builds gestures with hooks. usePanGesture takes a config object with callbacks, and Expo's worklets Babel plugin turns those callbacks into worklets, so they run on the UI thread next to the animation:
onUpdatefires for every finger movement. It copies the horizontal distance into a shared value, clamped so the row only moves left.onDeactivatefires when the finger lifts. Past 120 points, or flicked faster than 800 points a second, the row slides off and the appointment is cancelled; otherwise it springs back.activeOffsetXandfailOffsetYdecide who wins when the row sits in a scrolling list: the swipe only starts after 12 points of sideways movement, and gives way to the scroll view after 10 points of vertical movement.
Cancelling changes React state, and React state lives on the JavaScript thread. scheduleOnRN from react-native-worklets is the bridge: called from a worklet, it schedules a JavaScript function to run on the React Native thread.
cd ~/reanimated-queue-demo
cat > src/queue/swipeable-row.tsx <<'TSX'
import { StyleSheet, Text, useWindowDimensions, View } from 'react-native'
import { GestureDetector, usePanGesture } from 'react-native-gesture-handler'
import Animated, { Extrapolation, interpolate, useAnimatedStyle, useSharedValue, withSpring, withTiming } from 'react-native-reanimated'
import { scheduleOnRN } from 'react-native-worklets'
import type { Appointment } from './appointments'
const CANCEL_DISTANCE = 120
const CANCEL_SPEED = 800
type Props = {
appointment: Appointment
onCancel: (id: string) => void
badge?: React.ReactNode
}
export function SwipeableRow({ appointment, onCancel, badge }: Props) {
const { id, name, time, reason } = appointment
const { width } = useWindowDimensions()
const offset = useSharedValue(0)
const pan = usePanGesture({
testID: `swipe-${id}`,
activeOffsetX: [-12, 12],
failOffsetY: [-10, 10],
onUpdate: (event) => {
offset.value = Math.min(0, event.translationX)
},
onDeactivate: (event) => {
const farEnough = event.translationX < -CANCEL_DISTANCE || event.velocityX < -CANCEL_SPEED
if (farEnough) {
offset.value = withTiming(-width, { duration: 180 }, (finished) => {
// Back to the JavaScript thread to change React state.
if (finished) scheduleOnRN(onCancel, id)
})
} else {
offset.value = withSpring(0, { damping: 18, stiffness: 220 })
}
},
})
const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }))
// The "Cancel" label behind the row fades in as the row moves towards the threshold.
const hintStyle = useAnimatedStyle(() => ({
opacity: interpolate(offset.value, [-CANCEL_DISTANCE, 0], [1, 0], Extrapolation.CLAMP),
}))
return (
<View style={styles.container}>
<Animated.View style={[styles.hint, hintStyle]}>
<Text style={styles.hintText}>Cancel</Text>
</Animated.View>
<GestureDetector gesture={pan}>
<Animated.View
testID={`row-${id}`}
accessible
accessibilityLabel={`${time}, ${name}, ${reason}`}
// Swiping is not the only way: screen reader users get a Cancel action.
accessibilityActions={[{ name: 'cancel', label: 'Cancel appointment' }]}
onAccessibilityAction={(event) => {
if (event.nativeEvent.actionName === 'cancel') onCancel(id)
}}
style={[styles.row, rowStyle]}
>
<Text style={styles.time}>{time}</Text>
<View style={styles.text}>
<Text style={styles.name} numberOfLines={1}>
{name}
</Text>
<Text style={styles.reason}>{reason}</Text>
</View>
{badge}
</Animated.View>
</GestureDetector>
</View>
)
}
const styles = StyleSheet.create({
container: { backgroundColor: '#2a2d33' },
hint: { position: 'absolute', right: 16, top: 0, bottom: 0, justifyContent: 'center' },
hintText: { fontSize: 15, fontWeight: '600', color: '#ffffff' },
row: { flexDirection: 'row', alignItems: 'center', gap: 12, minHeight: 64, paddingHorizontal: 16, backgroundColor: '#ffffff', borderBottomWidth: 1, borderBottomColor: '#f1f2f4' },
time: { width: 48, fontSize: 14, color: '#6a707b' },
text: { flex: 1 },
name: { fontSize: 16, fontWeight: '600', color: '#0b0c0e' },
reason: { fontSize: 14, color: '#6a707b' },
})
TSXA swipe-only action is invisible to anyone who cannot see the row move or cannot make the gesture. The accessibilityActions entry gives TalkBack and VoiceOver users a "Cancel appointment" action on the same row.
Gesture Handler's Jest utilities drive a gesture without a finger. createGestureController steps through the gesture's life one call at a time, so you can check the row mid-drag, and fireGestureHandler plays a whole gesture at once. Every rendered gesture must sit inside a GestureHandlerRootView, in tests as in the app.
cd ~/reanimated-queue-demo
cat > src/queue/swipeable-row.test.tsx <<'TSX'
import { act, fireEvent, render, screen } from '@testing-library/react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { createGestureController, fireGestureHandler, getByGestureTestId } from 'react-native-gesture-handler/jest-utils'
import { getAnimatedStyle } from 'react-native-reanimated'
import { TODAY } from './appointments'
import { SwipeableRow } from './swipeable-row'
const kwame = TODAY.morning[1]
beforeEach(() => jest.useFakeTimers())
afterEach(() => jest.useRealTimers())
function renderRow(onCancel: (id: string) => void) {
return render(
<GestureHandlerRootView>
<SwipeableRow appointment={kwame} onCancel={onCancel} />
</GestureHandlerRootView>,
)
}
function rowOffset(): number {
const { transform } = getAnimatedStyle(screen.getByTestId('row-a2')) as { transform: { translateX: number }[] }
return transform[0].translateX
}
test('the row follows the finger, then springs back from a short swipe', async () => {
const onCancel = jest.fn()
await renderRow(onCancel)
const drag = createGestureController('swipe-a2')
await act(async () => {
drag.begin()
drag.activate()
drag.update({ translationX: -60 })
jest.advanceTimersByTime(16)
})
expect(rowOffset()).toBe(-60)
await act(async () => {
drag.end({ translationX: -60 })
jest.advanceTimersByTime(3000)
})
// A spring overshoots a little and settles; within a point of 0 is home.
expect(Math.abs(rowOffset())).toBeLessThan(1)
expect(onCancel).not.toHaveBeenCalled()
})
test('a long swipe slides the row away and cancels the appointment', async () => {
const onCancel = jest.fn()
await renderRow(onCancel)
await act(async () => {
fireGestureHandler(getByGestureTestId('swipe-a2'), [{ translationX: 0 }, { translationX: -200 }, { translationX: -200 }])
jest.advanceTimersByTime(500)
})
expect(onCancel).toHaveBeenCalledWith('a2')
})
test('screen reader users can cancel without swiping', async () => {
const onCancel = jest.fn()
await renderRow(onCancel)
await fireEvent(screen.getByLabelText('09:30, Kwame Mensah, Blood test'), 'accessibilityAction', {
nativeEvent: { actionName: 'cancel' },
})
expect(onCancel).toHaveBeenCalledWith('a2')
})
TSX
npx jest src/queue/swipeable-row --ciCheck it worked
Jest reports Tests: 3 passed, 3 total. Mid-drag the row sits exactly 60 points to the left, the same distance as the finger; after release it springs back to within a point of where it started, and only the long swipe or the accessibility action calls onCancel.
Step 6 · Animate rows entering and leaving the queue
When a row disappears from a list, the rows below it jump up to fill the gap. People lose their place. Layout animations fix this without any shared values: give each row's wrapper an entering animation for when it mounts, an exiting animation for when it unmounts, and a layout transition for when its position changes.
cd ~/reanimated-queue-demo
cat > src/queue/queue-list.tsx <<'TSX'
import { StyleSheet, Text, View } from 'react-native'
import Animated, { FadeInDown, FadeOutLeft, LinearTransition } from 'react-native-reanimated'
import type { Appointment } from './appointments'
import { NextBadge } from './next-badge'
import { SwipeableRow } from './swipeable-row'
type Props = {
appointments: readonly Appointment[]
onCancel: (id: string) => void
}
export function QueueList({ appointments, onCancel }: Props) {
if (appointments.length === 0) {
return <Text style={styles.empty}>No one waiting.</Text>
}
return (
<View>
{appointments.map((appointment, i) => (
<Animated.View
key={appointment.id}
entering={FadeInDown.duration(250)}
exiting={FadeOutLeft.duration(200)}
layout={LinearTransition.duration(250)}
>
<SwipeableRow appointment={appointment} onCancel={onCancel} badge={i === 0 ? <NextBadge /> : null} />
</Animated.View>
))}
</View>
)
}
const styles = StyleSheet.create({
empty: { padding: 24, textAlign: 'center', fontSize: 15, color: '#6a707b' },
})
TSXThree things make these animations behave:
- The
keyis the appointment's ID, never its position. Reanimated uses the key to tell which row left and which rows moved; with index keys, removing the first row looks like the last row leaving. - The animations sit on a wrapper, not on
SwipeableRow's own animated view, which is already busy following the finger. - The durations are short. At 200 to 250 milliseconds, a busy receptionist sees where things went without waiting for them.
For long lists, Animated.FlatList takes an itemLayoutAnimation prop that applies a layout transition to every item. A day's queue is short, so a plain View is enough here.
Test the list with a small harness that holds the queue in state:
cd ~/reanimated-queue-demo
cat > src/queue/queue-list.test.tsx <<'TSX'
import { act, fireEvent, render, screen } from '@testing-library/react-native'
import { useState } from 'react'
import { Pressable, Text } from 'react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { makeWalkIn, TODAY } from './appointments'
import { QueueList } from './queue-list'
beforeEach(() => jest.useFakeTimers())
afterEach(() => jest.useRealTimers())
function Harness() {
const [queue, setQueue] = useState(TODAY.morning)
return (
<GestureHandlerRootView>
<Pressable onPress={() => setQueue((q) => [...q, makeWalkIn(1)])}>
<Text>Add walk-in</Text>
</Pressable>
<QueueList appointments={queue} onCancel={(id) => setQueue((q) => q.filter((a) => a.id !== id))} />
</GestureHandlerRootView>
)
}
test('a walk-in joins the end of the queue', async () => {
await render(<Harness />)
await fireEvent.press(screen.getByText('Add walk-in'))
await act(async () => {
jest.advanceTimersByTime(300)
})
expect(screen.getByText('Walk-in 1')).toBeOnTheScreen()
expect(screen.getAllByText(/^(Check-up|Blood test|Vaccination|Walk-in)$/)).toHaveLength(4)
})
test('a cancelled appointment leaves, and the next one becomes Next', async () => {
await render(<Harness />)
await fireEvent(screen.getByLabelText('09:00, Adaeze Okonkwo, Check-up'), 'accessibilityAction', {
nativeEvent: { actionName: 'cancel' },
})
await act(async () => {
jest.advanceTimersByTime(300)
})
expect(screen.queryByText('Adaeze Okonkwo')).toBeNull()
expect(screen.getAllByText('Next')).toHaveLength(1)
expect(screen.getByLabelText('09:30, Kwame Mensah, Blood test')).toHaveTextContent(/Next/)
})
test('an empty queue says so', async () => {
await render(<QueueList appointments={[]} onCancel={() => {}} />)
expect(screen.getByText('No one waiting.')).toBeOnTheScreen()
})
TSX
npx jest src/queue/queue-list --ciCheck it worked
Jest reports Tests: 3 passed, 3 total. After a cancellation Adaeze's row is gone, and the Next badge has moved to Kwame, the new first row.
Step 7 · Respect the reduce-motion setting
Android and iOS both let people turn animations down: Reduce Motion under Accessibility, then Motion on iOS, and Remove animations in Android's accessibility settings (the exact menu varies between phone makers). People turn it on because movement makes them dizzy or sick, because it distracts them, or to make an old phone feel faster. Your app should honour it.
Here is what Reanimated does for you and what it leaves to you:
- Animation functions (
withTiming,withSpringand the rest) and layout animations (FadeInDown,LinearTransition) default toReduceMotion.System. With the setting on,withTimingandwithSpringjump straight to their end value and layout animations are skipped. The progress bar, the button spring, the row swipe and the list rows already behave. - CSS-style transitions and animations are not covered by that default. That is why
PeriodSwitchandNextBadgereaduseReducedMotion()and drop the duration to 0 and the pulse altogether.
useReducedMotion returns the setting as it was when the app started, and does not re-render when it changes, so after changing the setting on a phone, close the app fully and open it again.
Reduced motion should never hide information. The badge still says Next without its pulse, and a cancelled row still disappears. Add a test that renders the screen pieces as someone with reduced motion would see them:
cd ~/reanimated-queue-demo
cat > src/queue/reduced-motion.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { useReducedMotion } from 'react-native-reanimated'
import { TODAY } from './appointments'
import { pulseStyle } from './next-badge'
import { indicatorStyle, PeriodSwitch } from './period-switch'
import { QueueList } from './queue-list'
// Pretend the phone has reduced motion on. Keep the default export (Animated) as well.
jest.mock('react-native-reanimated', () => {
const actual = jest.requireActual('react-native-reanimated')
return { __esModule: true, ...actual, default: actual.default, useReducedMotion: jest.fn(() => true) }
})
test('with reduced motion on, the screen still says everything it did before', async () => {
await render(
<GestureHandlerRootView>
<PeriodSwitch value="afternoon" onChange={() => {}} />
<QueueList appointments={TODAY.afternoon} onCancel={() => {}} />
</GestureHandlerRootView>,
)
expect(useReducedMotion).toHaveBeenCalled()
expect(screen.getByRole('tab', { name: 'Afternoon', selected: true })).toBeOnTheScreen()
expect(screen.getByText('Next')).toBeOnTheScreen()
expect(screen.getByText('Oluwaseun Ògúnlẹ̀yẹ')).toBeOnTheScreen()
})
test('with reduced motion on, nothing transitions or loops', () => {
expect(indicatorStyle(1, true).transitionDuration).toBe(0)
expect(pulseStyle(true)).not.toHaveProperty('animationName')
})
TSX
npx jest src/queue/reduced-motion --ciCheck it worked
Jest reports Tests: 2 passed, 2 total. The components asked useReducedMotion for the setting, and with it on the tab, the badge text and the names are all still there.
Step 8 · Put the screen together and try it on a phone
The screen holds the queue in state and wires the pieces together. Calling the next patient moves the bar, cancelling removes a row, and the switch changes which half of the day you see.
cd ~/reanimated-queue-demo
cat > src/queue/queue-screen.tsx <<'TSX'
import { useCallback, useState } from 'react'
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { CallNextButton } from './call-next-button'
import { DayProgress } from './day-progress'
import { makeWalkIn, type Period, TODAY } from './appointments'
import { PeriodSwitch } from './period-switch'
import { QueueList } from './queue-list'
export function QueueScreen() {
const [period, setPeriod] = useState<Period>('morning')
const [queues, setQueues] = useState(TODAY)
const [seen, setSeen] = useState(0)
const [walkIns, setWalkIns] = useState(0)
const waiting = queues.morning.length + queues.afternoon.length
const current = queues[period]
const callNext = useCallback(() => {
setQueues((q) => ({ ...q, [period]: q[period].slice(1) }))
setSeen((n) => n + 1)
}, [period])
const cancel = useCallback(
(id: string) => setQueues((q) => ({ ...q, [period]: q[period].filter((a) => a.id !== id) })),
[period],
)
const addWalkIn = useCallback(() => {
const n = walkIns + 1
setWalkIns(n)
setQueues((q) => ({ ...q, [period]: [...q[period], makeWalkIn(n)] }))
}, [period, walkIns])
return (
<ScrollView contentContainerStyle={styles.content}>
<Text style={styles.title} accessibilityRole="header">
Today's queue
</Text>
<DayProgress seen={seen} total={seen + waiting} />
<PeriodSwitch value={period} onChange={setPeriod} />
<QueueList appointments={current} onCancel={cancel} />
<View style={styles.actions}>
<CallNextButton onPress={callNext} disabled={current.length === 0} />
<Pressable accessibilityRole="button" onPress={addWalkIn} style={styles.secondary}>
<Text style={styles.secondaryText}>Add walk-in</Text>
</Pressable>
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
content: { paddingVertical: 16, gap: 12, backgroundColor: '#ffffff' },
title: { paddingHorizontal: 16, fontSize: 24, fontWeight: '700', color: '#0b0c0e' },
actions: { gap: 8, paddingHorizontal: 16 },
secondary: { minHeight: 48, borderRadius: 8, borderWidth: 1, borderColor: '#d9dce1', alignItems: 'center', justifyContent: 'center' },
secondaryText: { fontSize: 16, color: '#2a2d33' },
})
TSX
cat > src/queue/queue-screen.test.tsx <<'TSX'
import { act, fireEvent, render, screen } from '@testing-library/react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { QueueScreen } from './queue-screen'
beforeEach(() => jest.useFakeTimers())
afterEach(() => jest.useRealTimers())
async function settle() {
await act(async () => {
jest.advanceTimersByTime(500)
})
}
test('calling, adding and cancelling keep the count right', async () => {
await render(
<GestureHandlerRootView>
<QueueScreen />
</GestureHandlerRootView>,
)
expect(screen.getByText('0 of 6 seen')).toBeOnTheScreen()
await fireEvent.press(screen.getByRole('button', { name: 'Call next patient' }))
await settle()
expect(screen.getByText('1 of 6 seen')).toBeOnTheScreen()
expect(screen.queryByText('Adaeze Okonkwo')).toBeNull()
await fireEvent.press(screen.getByRole('button', { name: 'Add walk-in' }))
await settle()
expect(screen.getByText('1 of 7 seen')).toBeOnTheScreen()
await fireEvent(screen.getByLabelText('Now, Walk-in 1, Walk-in'), 'accessibilityAction', {
nativeEvent: { actionName: 'cancel' },
})
await settle()
expect(screen.getByText('1 of 6 seen')).toBeOnTheScreen()
await fireEvent.press(screen.getByRole('tab', { name: 'Afternoon' }))
expect(screen.getByText('Fatou Diallo')).toBeOnTheScreen()
})
TSX
npx jest --ciGestures only work inside a GestureHandlerRootView, and it belongs as near the root of the app as possible. Replace the template's root layout with the same layout wrapped in one, and point the Explore tab at the queue:
cd ~/reanimated-queue-demo
cat > src/app/_layout.tsx <<'TSX'
import { DarkTheme, DefaultTheme, ThemeProvider } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { useColorScheme } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { AnimatedSplashOverlay } from '@/components/animated-icon';
import AppTabs from '@/components/app-tabs';
SplashScreen.preventAutoHideAsync();
export default function TabLayout() {
const colorScheme = useColorScheme();
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<AnimatedSplashOverlay />
<AppTabs />
</ThemeProvider>
</GestureHandlerRootView>
);
}
TSX
cat > src/app/explore.tsx <<'TSX'
import { SafeAreaView } from 'react-native-safe-area-context'
import { QueueScreen } from '../queue/queue-screen'
export default function QueueTab() {
return (
<SafeAreaView style={{ flex: 1, backgroundColor: '#ffffff' }} edges={['top']}>
<QueueScreen />
</SafeAreaView>
)
}
TSX
npx expo export --platform android
grep -a -c "Call next patient" dist/_expo/static/js/android/*.hbcBefore you reach for Reanimated in every case, know when React Native's own Animated is enough. With useNativeDriver: true, Animated also hands a running animation to the native side, so a fade or a slide that starts and ends without a finger in control runs smoothly. It cannot animate layout properties such as width with the native driver, it has no layout animations, and it cannot follow a gesture frame by frame on the UI thread. A one-off fade-in on a static screen can use Animated; a gesture, a layout change or a list is where Reanimated pays its way.
Now try it on a phone. Start the development server and open the app in Expo Go by scanning the QR code:
cd ~/reanimated-queue-demo
npx expo startOpen the Explore tab and try each animation: press and hold Call next patient, switch to Afternoon, add a walk-in, and swipe a row left part-way, then all the way. Then turn on Reduce Motion or Remove animations, close the app completely, open it again, and repeat. If you can, try it on a cheap Android phone with 2 or 3 GB of memory, the kind many of your users carry. Animations that run on the UI thread stay smooth there even while JavaScript is busy, which is the point of this tutorial.
Check it worked
The full Jest run reports seven test suites and Tests: 15 passed, 15 total. The export finishes with a bundle in dist, and grep prints 1 or more, from the button label. On the phone, the bar fills as you call patients, the button squeezes under your thumb, the indicator slides, new rows drop in from above, and a cancelled row slides away while the rows below glide up. With reduced motion on, every change happens at once and the badge stops pulsing, but nothing is missing.
Next steps
- Find what else slows a React Native app on cheap phones in speeding up a React Native app on a low-end Android phone.
- Keep forms usable when the keyboard opens with handling the keyboard and safe areas in React Native.
- Check the swipe's accessibility action with a real screen reader in making a React Native app work with screen readers.
- If you are new to Expo, start with creating your first Expo app.
- To delete the demo, remove the folder:
rm -rf ~/reanimated-queue-demo.
Related tutorials
- How to Create Your First React Native App with ExpoYou will create an Expo SDK 58 project with TypeScript, look at what the template gives you, run it on your phone or in a simulator, replace the home screen with a small counter of your own, and check from the command line that the project bundles and passes expo-doctor.
- Speed up a React Native app on a low-end Android phoneYou will measure a release build of your Expo app on a 2 to 3 GB Android phone, fix slow startup, dropped frames and re-render storms, and finish with a written performance budget you can check before every release.
- Handle the keyboard, notches and safe areas in React NativeYou will have an Expo SDK 58 chat screen and form that clear the status bar, notch and home indicator edge by edge, keep the message box above the keyboard, dismiss the keyboard on scroll and work in landscape, with Jest tests that fake each phone's insets.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials