fix(animated): keep user-registered listeners when an Animated node detaches (#57941)

Summary:
Fixes https://github.com/react/react-native/issues/43586.

`value.addListener(cb)` stops firing forever once any component bound to that `Animated.Value` unmounts, even though the value is still alive and still animating.

The chain:

1. [`AnimatedProps.__detach()`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Animated/nodes/AnimatedProps.js#L222-L235) loops `node.__removeChild(this)` on unmount.
2. [`AnimatedWithChildren.__removeChild()`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Animated/nodes/AnimatedWithChildren.js#L63-L65) does `if (this._children.length === 0) { this.__detach(); }` — the **value** detaches itself.
3. [`AnimatedNode.__detach()`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Animated/nodes/AnimatedNode.js#L51-L52) calls `this.removeAllListeners()`, which discards callbacks the **caller** registered.

An `Animated.Value` is owned by the caller and routinely outlives the components it drives. `addListener` / `removeListener` / `removeAllListeners` are documented public API. Detaching from the graph should not silently unregister the caller's callbacks.

### Why this is a regression, not intended behaviour

`removeAllListeners()` was added to `__detach()` in cd8319433 (Oct 2022) — but **behind a feature flag**, `removeListenersOnDetach`, which shipped as `() => false` in OSS:

```js
// v0.71.19 Libraries/Animated/nodes/AnimatedNode.js
__detach(): void {
  if (ReactNativeFeatureFlags.removeListenersOnDetach()) {
    this.removeAllListeners();
  }
  ...
```

49d5e7c51 (Nov 2022) then deleted the flag as an "unused feature flag" under `changelog: [internal]`, inlining the enabled branch. That flipped the OSS default and is exactly the 0.71 → 0.72 regression a second reporter bisected in [this comment](https://github.com/react/react-native/issues/43586#issuecomment-2112704213). The user-facing semantics change was never the intent of that commit.

### Why removing the call is safe

cd8319433's stated purpose was narrow:

> Removing listener on detached node leads to a red box, if the said node is `DiffClampAnimatedNode`. This is because calling `AnimatedNode.__getNativeTag()` makes native module call and creates node in native. This node is not completely initialised and red boxes […] The fix is make sure all listeners are removed before node is destroyed.

The requirement is **stop listening to native value updates before the native node is dropped**, not *discard the caller's callbacks*. Those are two different things, and today they are cleanly separable:

- `AnimatedValue.removeAllListeners()` clears `_listeners` (caller-owned) **and** calls `this._updateSubscription?.remove()` (node-owned: the `onAnimatedValueUpdate` emitter subscription plus `stopListeningToAnimatedNodeValue`).
- Only the second belongs in `__detach()`.

The 2022 hazard is also structurally gone. In 0.71, `_stopListeningForNativeValueUpdates()` called `NativeAnimatedAPI.stopListeningToAnimatedNodeValue(this.__getNativeTag())` — on a detached node `__getNativeTag()` resurrects a half-initialised native node, which is the red box. Today's [`_updateSubscription.remove()`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Animated/nodes/AnimatedValue.js#L182-L192) closes over a local `nativeTag` const and never calls `__getNativeTag()`. This PR adds no new `__getNativeTag()` call on any path.

So `__detach()` now tears down only what the node owns, and the ordering that mattered (stop listening → `dropAnimatedNode`) is preserved.

### Does this leak?

No framework-owned resource is retained.

- The `onAnimatedValueUpdate` `NativeEventEmitter` subscription and the native `startListeningToAnimatedNodeValue` state are still released on detach — asserted by a new test.
- `_listeners` lives on the `AnimatedValue` itself. React Native keeps no registry of JS `Animated` values, so a value is reachable only from user code. Drop the value and the listeners go with it.
- If the caller deliberately keeps a value alive past its components, the retained graph is exactly what their own closures capture, and `removeListener()` / `removeAllListeners()` are the documented way to release it.

Both in-tree consumers that register listeners on an `AnimatedValue` already clean up after themselves and never relied on `__detach()` doing it — [`ScrollViewStickyHeader`](https://github.com/react/react-native/blob/main/packages/react-native/Libraries/Components/ScrollView/ScrollViewStickyHeader.js#L247-L251) and [`createAnimatedPropsHook`](https://github.com/react/react-native/blob/main/packages/react-native/src/private/animated/createAnimatedPropsHook.js#L221-L223), both in effect cleanups.

Honest behavioural delta: a caller who adds a listener on every mount and never removes it, on a value that outlives those components, will now accumulate listeners. Previously the accumulation was hidden by the very bug being fixed. Note the old behaviour was not a dependable cleanup mechanism either — it only fired when the *last* child detached, and never for listeners added after detach.

## Relationship to https://github.com/react/react-native/issues/57170

They overlap and **cannot both land as-is**.

- Textual: https://github.com/react/react-native/issues/57170 rewrites `AnimatedValue.__detach()`, so `git apply --3way` of its patch onto this branch conflicts in `AnimatedValue.js`.
- Semantic: https://github.com/react/react-native/issues/57170's new tests assert the behaviour this PR changes (`__detach()` → `removeAllListeners()` on the r/g/b/a channels). Those assertions would need rewriting on top of this change.

They also address the same underlying defect from opposite ends. https://github.com/react/react-native/issues/57170 clamps `_listenerCount` so it cannot go negative. I measured where the negative count comes from — `__detach()` zeroing `_listenerCount` out from under a caller who still holds a listener id:

| flow | `main` | this PR |
|---|---|---|
| `addListener` → `__detach()` | `_listenerCount === 0` | `_listenerCount === 1` |
| … then `removeListener(id)` | `_listenerCount === -1` | `_listenerCount === 0` |

This PR removes that root cause, so the count stays consistent without clamping. I have no opinion on whether the clamp is still wanted as defence-in-depth — flagging the interaction for whoever reviews both.

## Changelog

[GENERAL] [FIXED] - Animated - `Animated.Value` listeners registered with `addListener` are no longer removed when a component bound to the value unmounts

Pull Request resolved: https://github.com/react/react-native/pull/57941

Test Plan:
Tests added:

- `packages/react-native/Libraries/Animated/__tests__/Animated-test.js`
  - `should keep listeners when the last attached node detaches` — node-graph level.
  - `should keep listeners when a bound component unmounts` — the user-visible path: render `<Animated.View style={{transform: [{translateX: value}]}} />`, unmount it, then `setValue(42)` and assert the listener fires.
- `packages/react-native/src/private/animated/__tests__/AnimatedNative-test.js`
  - `should stop listening to native updates on unmount, but keep listeners` — guards what `removeAllListeners()` was there for: after unmount, `stopListeningToAnimatedNodeValue(tag)` and `dropAnimatedNode(tag)` are still called and a subsequent `onAnimatedValueUpdate` emission does **not** reach the listener, while `hasListeners()` stays `true`.
  - `should resume delivering native updates when remounted` — native driver end to end: unmount, remount, and native updates on the new tag reach the original listener.

Counterfactual — reverting only the two source files and keeping the tests:

```
$ git checkout -- packages/react-native/Libraries/Animated/nodes/AnimatedNode.js \
                  packages/react-native/Libraries/Animated/nodes/AnimatedValue.js
$ yarn jest packages/react-native/Libraries/Animated/__tests__/Animated-test.js \
            packages/react-native/src/private/animated/__tests__/AnimatedNative-test.js

  ● Native Animated › Animated Listeners › should stop listening to native updates on unmount, but keep listeners
  ● Native Animated › Animated Listeners › should resume delivering native updates when remounted
  ● Animated › Animated Listeners › should keep listeners when the last attached node detaches
  ● Animated › Animated Listeners › should keep listeners when a bound component unmounts

Test Suites: 2 failed, 2 total
Tests:       4 failed, 97 passed, 101 total
```

All four fail without the change; the 97 pre-existing tests in those two files pass either way.

Full suite, with the change restored:

```
$ yarn test
Test Suites: 218 passed, 218 total
Tests:       1 skipped, 5589 passed, 5590 total

$ yarn flow-check
Found 0 errors

$ yarn lint
Done in 9.20s.   (eslint --max-warnings 0 .)
```

Baseline on `main` measured on the same checkout: 218 suites, 5585 passed / 1 skipped — this PR adds exactly the 4 tests above.

Not verified: I did not run this on a device or simulator, so the fix is verified through the JS graph and the mocked native-driver harness rather than against the reporter's app.

Reviewed By: javache

Differential Revision: D116040594

Pulled By: zeyap

fbshipit-source-id: b9bcb18c8ca01fa28a1dd8ff1c1737c15627d520
This commit is contained in:
Bao Nguyen authored and meta-codesync[bot] committed 2026-08-19 11:24:50 -07:00
1 parent 4c022bbf7d
commit 14938717e6
7 files changed
+128 -3

No files matched your search

@@ -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(
<Animated.View style={{transform: [{translateX: value1}]}} />,
);
await unmount(root);
jest.runAllTicks();
value1.setValue(42);
expect(listener).toBeCalledWith({value: 42});
expect(listener.mock.calls.length).toBe(1);
});
});
describe('Animated Diff Clamp', () => {
@@ -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);
});
@@ -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;
@@ -124,6 +124,9 @@ export default class AnimatedValue extends AnimatedWithChildren {
});
}
this.stopAnimation();
if (ReactNativeFeatureFlags.animatedKeepListenersOnDetach()) {
this._updateSubscription?.remove();
}
super.__detach();
}
@@ -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: {
@@ -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(<Animated.View style={{opacity: value1}} />);
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(<Animated.View style={{opacity: value1}} />);
await unmount(root);
jest.runAllTicks();
await create(<Animated.View style={{opacity: value1}} />);
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', () => {
@@ -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<<bafad194115f60dcf22f64015fe64856>>
* @generated SignedSource<<fbab08ee89a2969b45034a45b6425581>>
* @flow strict
* @noformat
*/
@@ -31,6 +31,7 @@ export type ReactNativeFeatureFlagsJsOnly = Readonly<{
jsOnlyTestFlag: Getter<boolean>,
animatedDeferStartOfTimingAnimations: Getter<boolean>,
animatedForceNativeDriver: Getter<boolean>,
animatedKeepListenersOnDetach: Getter<boolean>,
animatedShouldSyncValueBeforeStartCallback: Getter<boolean>,
deferFlatListFocusChangeRenderUpdate: Getter<boolean>,
enableImperativeEvents: Getter<boolean>,
@@ -152,6 +153,11 @@ export const animatedDeferStartOfTimingAnimations: Getter<boolean> = createJavaS
*/
export const animatedForceNativeDriver: Getter<boolean> = 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<boolean> = 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.
*/