Skip to content

Commit 5de6d23

Browse files
authored
Keep ReanimatedSwipeable native handlers stable when event callbacks change (#4466)
## Description Fixes #3307 Passing inline `onSwipeableOpen` / `onSwipeableClose` (or the other event props) to `ReanimatedSwipeable` made list scrolling stutter, even when the callbacks were empty. Those functions sat in the worklet/`useCallback` dependency chain, so a new identity on every parent render rebuilt the pan and tap gesture configs and reconfigured the native handlers. This change: - keeps the latest user callbacks behind stable wrappers (`useEventCallback`) - memoizes the tap/pan configs so native handlers are only updated when gesture settings actually change - still invokes the most recent callback after a callback-only rerender `ReanimatedDrawerLayout` has a similar pattern, but it is typically a single instance per screen rather than a list row, so it is left untouched here. ## Test plan - [x] `yarn test src/__tests__/reanimatedSwipeableCallbacks.test.tsx` — native `setGestureHandlerConfig` is not called again when only event callback identities change - [x] same file — `close()` after a callback-only rerender invokes the latest `onSwipeableWillClose` - [x] sabotage: bypassing `useEventCallback` makes the identity test fail (`2` → `4` `setConfig` calls) - [x] `yarn test` — 19 suites / 158 tests pass - [x] `yarn lint:js` (no new errors) and `yarn ts-check` - [x] Please confirm scrolling a `FlatList`/`FlashList` of `ReanimatedSwipeable` rows with inline `onSwipeableOpen={() => {}}` no longer drops JS FPS
1 parent 6f73a7e commit 5de6d23

2 files changed

Lines changed: 297 additions & 38 deletions

File tree

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
import { render } from '@testing-library/react-native';
2+
import React from 'react';
3+
import { Text } from 'react-native';
4+
import { scheduleOnRN } from 'react-native-worklets';
5+
6+
import GestureHandlerRootView from '../components/GestureHandlerRootView';
7+
import type {
8+
SwipeableMethods,
9+
SwipeableProps,
10+
} from '../components/ReanimatedSwipeable';
11+
import ReanimatedSwipeable from '../components/ReanimatedSwipeable';
12+
import RNGestureHandlerModule from '../RNGestureHandlerModule';
13+
14+
jest.mock('react-native-reanimated', () => {
15+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
16+
const ReactNative = jest.requireActual('react-native');
17+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
18+
const ReactActual = jest.requireActual('react');
19+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
20+
const AnimatedView = ReactNative.View;
21+
22+
return {
23+
__esModule: true,
24+
default: {
25+
View: AnimatedView,
26+
createAnimatedComponent: (component: unknown) => component,
27+
},
28+
View: AnimatedView,
29+
createAnimatedComponent: (component: unknown) => component,
30+
interpolate: (value: number) => value,
31+
isSharedValue: () => false,
32+
measure: () => null,
33+
ReduceMotion: { System: 'system' },
34+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
35+
useAnimatedRef: () => ReactActual.useRef(null),
36+
useAnimatedStyle: () => ({}),
37+
useSharedValue: (init: unknown) => {
38+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
39+
const ref = ReactActual.useRef({ value: init });
40+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access
41+
return ref.current;
42+
},
43+
withSpring: (to: unknown) => to,
44+
};
45+
});
46+
47+
jest.mock('react-native-worklets', () => {
48+
const WorkletsMock = jest.requireActual<
49+
Record<string, unknown> & { scheduleOnRN: typeof scheduleOnRN }
50+
>('react-native-worklets/src/mock');
51+
52+
return {
53+
...WorkletsMock,
54+
scheduleOnRN: jest.fn(WorkletsMock.scheduleOnRN),
55+
};
56+
});
57+
58+
async function flushNativeOps() {
59+
await new Promise<void>((resolve) => {
60+
setTimeout(resolve, 0);
61+
});
62+
await new Promise<void>((resolve) => {
63+
queueMicrotask(resolve);
64+
});
65+
await new Promise<void>((resolve) => {
66+
setImmediate(resolve);
67+
});
68+
}
69+
70+
function SwipeableRow({
71+
swipeableRef,
72+
onSwipeableOpen,
73+
onSwipeableClose,
74+
onSwipeableWillOpen,
75+
onSwipeableWillClose,
76+
onSwipeableOpenStartDrag,
77+
onSwipeableCloseStartDrag,
78+
}: {
79+
swipeableRef?: React.Ref<SwipeableMethods>;
80+
onSwipeableOpen: NonNullable<SwipeableProps['onSwipeableOpen']>;
81+
onSwipeableClose: NonNullable<SwipeableProps['onSwipeableClose']>;
82+
onSwipeableWillOpen: NonNullable<SwipeableProps['onSwipeableWillOpen']>;
83+
onSwipeableWillClose: NonNullable<SwipeableProps['onSwipeableWillClose']>;
84+
onSwipeableOpenStartDrag: NonNullable<
85+
SwipeableProps['onSwipeableOpenStartDrag']
86+
>;
87+
onSwipeableCloseStartDrag: NonNullable<
88+
SwipeableProps['onSwipeableCloseStartDrag']
89+
>;
90+
}) {
91+
const fallbackRef = React.useRef<SwipeableMethods>(null);
92+
93+
return (
94+
<GestureHandlerRootView>
95+
<ReanimatedSwipeable
96+
ref={swipeableRef ?? fallbackRef}
97+
renderRightActions={() => <Text>Delete</Text>}
98+
onSwipeableOpen={onSwipeableOpen}
99+
onSwipeableClose={onSwipeableClose}
100+
onSwipeableWillOpen={onSwipeableWillOpen}
101+
onSwipeableWillClose={onSwipeableWillClose}
102+
onSwipeableOpenStartDrag={onSwipeableOpenStartDrag}
103+
onSwipeableCloseStartDrag={onSwipeableCloseStartDrag}>
104+
<Text>Row</Text>
105+
</ReanimatedSwipeable>
106+
</GestureHandlerRootView>
107+
);
108+
}
109+
110+
function inlineCallbacks() {
111+
return {
112+
onSwipeableOpen: () => undefined,
113+
onSwipeableClose: () => undefined,
114+
onSwipeableWillOpen: () => undefined,
115+
onSwipeableWillClose: () => undefined,
116+
onSwipeableOpenStartDrag: () => undefined,
117+
onSwipeableCloseStartDrag: () => undefined,
118+
};
119+
}
120+
121+
describe('ReanimatedSwipeable callback identity', () => {
122+
let setConfigSpy: jest.SpyInstance;
123+
124+
beforeEach(() => {
125+
jest.clearAllMocks();
126+
setConfigSpy = jest.spyOn(
127+
RNGestureHandlerModule,
128+
'setGestureHandlerConfig'
129+
);
130+
jest.mocked(scheduleOnRN).mockClear();
131+
});
132+
133+
afterEach(() => {
134+
setConfigSpy.mockRestore();
135+
});
136+
137+
test('does not reconfigure native handlers when only event callback identities change', async () => {
138+
const { rerender } = render(<SwipeableRow {...inlineCallbacks()} />);
139+
await flushNativeOps();
140+
141+
const callsAfterMount = setConfigSpy.mock.calls.length;
142+
expect(callsAfterMount).toBeGreaterThan(0);
143+
144+
rerender(<SwipeableRow {...inlineCallbacks()} />);
145+
await flushNativeOps();
146+
147+
expect(setConfigSpy.mock.calls.length).toBe(callsAfterMount);
148+
});
149+
150+
test('invokes the latest event callbacks after a callback-only rerender', async () => {
151+
const first = {
152+
...inlineCallbacks(),
153+
onSwipeableWillClose: jest.fn(),
154+
};
155+
const second = {
156+
...inlineCallbacks(),
157+
onSwipeableWillClose: jest.fn(),
158+
};
159+
const swipeableRef = React.createRef<SwipeableMethods>();
160+
161+
const { rerender } = render(
162+
<SwipeableRow {...first} swipeableRef={swipeableRef} />
163+
);
164+
165+
swipeableRef.current?.close();
166+
await flushNativeOps();
167+
expect(first.onSwipeableWillClose).toHaveBeenCalledTimes(1);
168+
expect(second.onSwipeableWillClose).not.toHaveBeenCalled();
169+
170+
rerender(<SwipeableRow {...second} swipeableRef={swipeableRef} />);
171+
172+
swipeableRef.current?.close();
173+
await flushNativeOps();
174+
expect(first.onSwipeableWillClose).toHaveBeenCalledTimes(1);
175+
expect(second.onSwipeableWillClose).toHaveBeenCalledTimes(1);
176+
});
177+
178+
test('does not schedule JS work when event callbacks are absent', async () => {
179+
const swipeableRef = React.createRef<SwipeableMethods>();
180+
181+
render(
182+
<GestureHandlerRootView>
183+
<ReanimatedSwipeable
184+
ref={swipeableRef}
185+
renderRightActions={() => <Text>Delete</Text>}>
186+
<Text>Row</Text>
187+
</ReanimatedSwipeable>
188+
</GestureHandlerRootView>
189+
);
190+
191+
swipeableRef.current?.close();
192+
await flushNativeOps();
193+
expect(scheduleOnRN).not.toHaveBeenCalled();
194+
});
195+
});

‎packages/react-native-gesture-handler/src/components/ReanimatedSwipeable/ReanimatedSwipeable.tsx‎

Lines changed: 102 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import React, {
44
useEffect,
55
useImperativeHandle,
66
useMemo,
7+
useRef,
78
} from 'react';
89
import type { LayoutChangeEvent } from 'react-native';
910
import { I18nManager, StyleSheet, View } from 'react-native';
@@ -45,6 +46,21 @@ const DEFAULT_OVERSHOOT_FRICTION = 1;
4546
const DEFAULT_DRAG_OFFSET = 10;
4647
const DEFAULT_ENABLE_TRACKING_TWO_FINGER_GESTURE = false;
4748

49+
function useEventCallback<Args extends unknown[]>(
50+
callback: ((...args: Args) => void) | undefined
51+
): ((...args: Args) => void) | undefined {
52+
const callbackRef = useRef(callback);
53+
callbackRef.current = callback;
54+
55+
const stableCallback = useCallback((...args: Args) => {
56+
callbackRef.current?.(...args);
57+
}, []);
58+
59+
// Keep a stable wrapper only while a user callback exists, so the existing
60+
// truthiness checks can still skip `scheduleOnRN` when the prop is absent.
61+
return callback ? stableCallback : undefined;
62+
}
63+
4864
const Swipeable = (props: SwipeableProps) => {
4965
const {
5066
ref,
@@ -63,12 +79,12 @@ const Swipeable = (props: SwipeableProps) => {
6379
dragOffsetFromRight = -DEFAULT_DRAG_OFFSET,
6480
friction = DEFAULT_FRICTION,
6581
overshootFriction = DEFAULT_OVERSHOOT_FRICTION,
66-
onSwipeableOpenStartDrag,
67-
onSwipeableCloseStartDrag,
68-
onSwipeableWillOpen,
69-
onSwipeableWillClose,
70-
onSwipeableOpen,
71-
onSwipeableClose,
82+
onSwipeableOpenStartDrag: onSwipeableOpenStartDragProp,
83+
onSwipeableCloseStartDrag: onSwipeableCloseStartDragProp,
84+
onSwipeableWillOpen: onSwipeableWillOpenProp,
85+
onSwipeableWillClose: onSwipeableWillCloseProp,
86+
onSwipeableOpen: onSwipeableOpenProp,
87+
onSwipeableClose: onSwipeableCloseProp,
7288
renderLeftActions,
7389
renderRightActions,
7490
simultaneousWith,
@@ -78,6 +94,17 @@ const Swipeable = (props: SwipeableProps) => {
7894
...remainingProps
7995
} = props;
8096

97+
const onSwipeableOpenStartDrag = useEventCallback(
98+
onSwipeableOpenStartDragProp
99+
);
100+
const onSwipeableCloseStartDrag = useEventCallback(
101+
onSwipeableCloseStartDragProp
102+
);
103+
const onSwipeableWillOpen = useEventCallback(onSwipeableWillOpenProp);
104+
const onSwipeableWillClose = useEventCallback(onSwipeableWillCloseProp);
105+
const onSwipeableOpen = useEventCallback(onSwipeableOpenProp);
106+
const onSwipeableClose = useEventCallback(onSwipeableCloseProp);
107+
81108
if (__DEV__) {
82109
const checkValue = (value: SharedValueOrT<number>) => {
83110
'worklet';
@@ -512,30 +539,13 @@ const Swipeable = (props: SwipeableProps) => {
512539

513540
const dragStarted = useSharedValue<boolean>(false);
514541

515-
const tapGesture = useTapGesture({
516-
shouldCancelWhenOutside: true,
517-
enabled: shouldEnableTap,
518-
simultaneousWith,
519-
requireToFail,
520-
block,
521-
onActivate: () => {
522-
'worklet';
523-
if (rowState.value !== 0) {
524-
close();
525-
}
526-
},
527-
});
542+
const handleFinalize = useCallback(() => {
543+
'worklet';
544+
dragStarted.value = false;
545+
}, [dragStarted]);
528546

529-
const panGesture = usePanGesture({
530-
enabled: enabled ?? true,
531-
enableTrackpadTwoFingerGesture: enableTrackpadTwoFingerGesture,
532-
activeOffsetX: [dragOffsetFromRight, dragOffsetFromLeft],
533-
simultaneousWith,
534-
requireToFail,
535-
block,
536-
hitSlop: hitSlop,
537-
onActivate: updateElementWidths,
538-
onUpdate: (event: PanGestureActiveEvent) => {
547+
const handleUpdate = useCallback(
548+
(event: PanGestureActiveEvent) => {
539549
'worklet';
540550
userDrag.value = event.translationX;
541551

@@ -559,15 +569,69 @@ const Swipeable = (props: SwipeableProps) => {
559569

560570
updateAnimatedEvent();
561571
},
562-
onDeactivate: (event: PanGestureActiveEvent) => {
563-
'worklet';
564-
handleRelease(event);
565-
},
566-
onFinalize: () => {
567-
'worklet';
568-
dragStarted.value = false;
569-
},
570-
});
572+
[
573+
dragStarted,
574+
onSwipeableCloseStartDrag,
575+
onSwipeableOpenStartDrag,
576+
rowState,
577+
updateAnimatedEvent,
578+
userDrag,
579+
]
580+
);
581+
582+
const tapConfig = useMemo(
583+
() => ({
584+
shouldCancelWhenOutside: true,
585+
enabled: shouldEnableTap,
586+
simultaneousWith,
587+
requireToFail,
588+
block,
589+
onActivate: () => {
590+
'worklet';
591+
if (rowState.value !== 0) {
592+
close();
593+
}
594+
},
595+
}),
596+
[block, close, requireToFail, rowState, shouldEnableTap, simultaneousWith]
597+
);
598+
599+
const tapGesture = useTapGesture(tapConfig);
600+
601+
const panConfig = useMemo(
602+
() => ({
603+
enabled: enabled ?? true,
604+
enableTrackpadTwoFingerGesture: enableTrackpadTwoFingerGesture,
605+
activeOffsetX: [dragOffsetFromRight, dragOffsetFromLeft] as [
606+
typeof dragOffsetFromRight,
607+
typeof dragOffsetFromLeft,
608+
],
609+
simultaneousWith,
610+
requireToFail,
611+
block,
612+
hitSlop: hitSlop,
613+
onActivate: updateElementWidths,
614+
onUpdate: handleUpdate,
615+
onDeactivate: handleRelease,
616+
onFinalize: handleFinalize,
617+
}),
618+
[
619+
block,
620+
dragOffsetFromLeft,
621+
dragOffsetFromRight,
622+
enableTrackpadTwoFingerGesture,
623+
enabled,
624+
handleFinalize,
625+
handleRelease,
626+
handleUpdate,
627+
hitSlop,
628+
requireToFail,
629+
simultaneousWith,
630+
updateElementWidths,
631+
]
632+
);
633+
634+
const panGesture = usePanGesture(panConfig);
571635

572636
useImperativeHandle(ref, () => swipeableMethods, [swipeableMethods]);
573637

0 commit comments

Comments
 (0)