diff --git a/packages/react-native/Libraries/Animated/__tests__/Animated-test.js b/packages/react-native/Libraries/Animated/__tests__/Animated-test.js index e99c9a90acb..3d4b8c70fdc 100644 --- a/packages/react-native/Libraries/Animated/__tests__/Animated-test.js +++ b/packages/react-native/Libraries/Animated/__tests__/Animated-test.js @@ -1102,6 +1102,39 @@ describe('Animated', () => { value1.setValue(7); expect(listener.mock.calls.length).toBe(4); }); + + it('should keep listeners when the last attached node detaches', () => { + const value1 = new Animated.Value(0); + const listener = jest.fn(); + value1.addListener(listener); + + const node = new AnimatedProps({style: {opacity: value1}}, () => {}); + node.__attach(); + node.__detach(); + + expect(value1.__getChildren().length).toBe(0); + expect(value1.hasListeners()).toBe(true); + + value1.setValue(42); + expect(listener).toBeCalledWith({value: 42}); + expect(listener.mock.calls.length).toBe(1); + }); + + it('should keep listeners when a bound component unmounts', async () => { + const value1 = new Animated.Value(0); + const listener = jest.fn(); + value1.addListener(listener); + + const root = await create( + , + ); + await unmount(root); + jest.runAllTicks(); + + value1.setValue(42); + expect(listener).toBeCalledWith({value: 42}); + expect(listener.mock.calls.length).toBe(1); + }); }); describe('Animated Diff Clamp', () => { diff --git a/packages/react-native/Libraries/Animated/__tests__/AnimatedValue-itest.js b/packages/react-native/Libraries/Animated/__tests__/AnimatedValue-itest.js index 1984ef56ee5..b0781d4f865 100644 --- a/packages/react-native/Libraries/Animated/__tests__/AnimatedValue-itest.js +++ b/packages/react-native/Libraries/Animated/__tests__/AnimatedValue-itest.js @@ -4,6 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * + * @fantom_flags animatedKeepListenersOnDetach:* * @flow strict-local * @format */ @@ -11,6 +12,7 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; import NativeAnimatedHelper from '../../../src/private/animated/NativeAnimatedHelper'; +import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags'; import AnimatedValue from '../nodes/AnimatedValue'; describe('AnimatedValue', () => { @@ -128,7 +130,12 @@ describe('AnimatedValue', () => { node.addListener(callbackB); emitMockUpdate(node, 456, 60); - expect(callbackA).toBeCalledTimes(1); + if (ReactNativeFeatureFlags.animatedKeepListenersOnDetach()) { + // `callbackA` survives the detach and is resubscribed on re-attach. + expect(callbackA).toBeCalledTimes(2); + } else { + expect(callbackA).toBeCalledTimes(1); + } expect(callbackB).toBeCalledTimes(1); }); diff --git a/packages/react-native/Libraries/Animated/nodes/AnimatedNode.js b/packages/react-native/Libraries/Animated/nodes/AnimatedNode.js index d4e2d7db8d8..a7414bd4821 100644 --- a/packages/react-native/Libraries/Animated/nodes/AnimatedNode.js +++ b/packages/react-native/Libraries/Animated/nodes/AnimatedNode.js @@ -11,6 +11,7 @@ import type {PlatformConfig} from '../AnimatedPlatformConfig'; import NativeAnimatedHelper from '../../../src/private/animated/NativeAnimatedHelper'; +import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags'; import invariant from 'invariant'; export type ValueListenerCallback = (state: {value: number}) => unknown; @@ -49,7 +50,9 @@ export default class AnimatedNode { __attach(): void {} __detach(): void { - this.removeAllListeners(); + if (!ReactNativeFeatureFlags.animatedKeepListenersOnDetach()) { + this.removeAllListeners(); + } if (this.__isNative && this.__nativeTag != null) { NativeAnimatedHelper.API.dropAnimatedNode(this.__nativeTag); this.__nativeTag = undefined; diff --git a/packages/react-native/Libraries/Animated/nodes/AnimatedValue.js b/packages/react-native/Libraries/Animated/nodes/AnimatedValue.js index c393e27cf3e..74ce65ae364 100644 --- a/packages/react-native/Libraries/Animated/nodes/AnimatedValue.js +++ b/packages/react-native/Libraries/Animated/nodes/AnimatedValue.js @@ -124,6 +124,9 @@ export default class AnimatedValue extends AnimatedWithChildren { }); } this.stopAnimation(); + if (ReactNativeFeatureFlags.animatedKeepListenersOnDetach()) { + this._updateSubscription?.remove(); + } super.__detach(); } diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index 412db93053d..421b5fe0360 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -1001,6 +1001,17 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, + animatedKeepListenersOnDetach: { + defaultValue: true, + metadata: { + dateAdded: '2026-08-14', + description: + 'When enabled, detaching an animated node from the graph retains listeners registered with `addListener` instead of removing them, so an `Animated.Value` that outlives the components using it still notifies them once it is attached again.', + expectedReleaseValue: true, + purpose: 'experimentation', + }, + ossReleaseStage: 'none', + }, animatedShouldSyncValueBeforeStartCallback: { defaultValue: true, metadata: { diff --git a/packages/react-native/src/private/animated/__tests__/AnimatedNative-test.js b/packages/react-native/src/private/animated/__tests__/AnimatedNative-test.js index 0141d70dd6c..805325fd737 100644 --- a/packages/react-native/src/private/animated/__tests__/AnimatedNative-test.js +++ b/packages/react-native/src/private/animated/__tests__/AnimatedNative-test.js @@ -286,6 +286,68 @@ describe('Native Animated', () => { }); expect(listener).toHaveBeenCalledTimes(4); }); + + it('should stop listening to native updates on unmount, but keep listeners', async () => { + const {Animated, NativeAnimatedHelper} = importModules(); + + const value1 = new Animated.Value(0, {useNativeDriver: true}); + const listener = jest.fn(); + value1.addListener(listener); + + const tag = value1.__getNativeTag(); + expect( + NativeAnimatedModule.startListeningToAnimatedNodeValue, + ).toHaveBeenCalledWith(tag); + + const root = await create(); + await unmount(root); + jest.runAllTicks(); + + expect( + NativeAnimatedModule.stopListeningToAnimatedNodeValue, + ).toHaveBeenCalledWith(tag); + expect(NativeAnimatedModule.dropAnimatedNode).toHaveBeenCalledWith(tag); + NativeAnimatedHelper.nativeEventEmitter.emit('onAnimatedValueUpdate', { + value: 42, + tag, + }); + expect(listener).not.toHaveBeenCalled(); + expect(value1.hasListeners()).toBe(true); + }); + + it('should resume delivering native updates when remounted', async () => { + const {Animated, NativeAnimatedHelper} = importModules(); + + const value1 = new Animated.Value(0, {useNativeDriver: true}); + const listener = jest.fn(); + value1.addListener(listener); + + const initialTag = value1.__getNativeTag(); + const root = await create(); + await unmount(root); + jest.runAllTicks(); + + await create(); + jest.runAllTicks(); + + // The node is recreated with a new tag, which the retained listener must + // be resubscribed to. + const tag = value1.__getNativeTag(); + expect(tag).not.toBe(initialTag); + expect( + NativeAnimatedModule.startListeningToAnimatedNodeValue, + ).toHaveBeenCalledWith(tag); + expect( + NativeAnimatedModule.startListeningToAnimatedNodeValue, + ).toHaveBeenCalledTimes(2); + + NativeAnimatedHelper.nativeEventEmitter.emit('onAnimatedValueUpdate', { + value: 42, + tag, + }); + expect(listener).toBeCalledWith({value: 42}); + expect(listener).toHaveBeenCalledTimes(1); + }); }); describe('Animated Events', () => { diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index 3e9760473ca..0c0a8e54e61 100644 --- a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js +++ b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> * @flow strict * @noformat */ @@ -31,6 +31,7 @@ export type ReactNativeFeatureFlagsJsOnly = Readonly<{ jsOnlyTestFlag: Getter, animatedDeferStartOfTimingAnimations: Getter, animatedForceNativeDriver: Getter, + animatedKeepListenersOnDetach: Getter, animatedShouldSyncValueBeforeStartCallback: Getter, deferFlatListFocusChangeRenderUpdate: Getter, enableImperativeEvents: Getter, @@ -152,6 +153,11 @@ export const animatedDeferStartOfTimingAnimations: Getter = createJavaS */ export const animatedForceNativeDriver: Getter = createJavaScriptFlagGetter('animatedForceNativeDriver', false); +/** + * When enabled, detaching an animated node from the graph retains listeners registered with `addListener` instead of removing them, so an `Animated.Value` that outlives the components using it still notifies them once it is attached again. + */ +export const animatedKeepListenersOnDetach: Getter = createJavaScriptFlagGetter('animatedKeepListenersOnDetach', true); + /** * When a useNativeDriver animation completes, syncs the JS-side AnimatedValue with the post-animation value BEFORE invoking the user-supplied start({finished}) callback. Without the flag, the callback observes the pre-animation value, which can cause downstream re-renders to read stale interpolation outputs. */