From 84ee4d4643d50ae00c381f837fbf628e0ee5acfe Mon Sep 17 00:00:00 2001 From: Ruslan Lesiutin Date: Fri, 7 Nov 2025 14:18:11 -0800 Subject: [PATCH] Fix cascading update (#54438) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/54438 # Changelog: [Internal] `LogBoxStateSubscription` subscribed to state updates in a mount effect. This callback could be called instantly on subscription initiation, which would cause a cascading update => setState in mount effect [1]. This diff changes the approach, the state is initialized before mount and the callback is not called synchronously on initialization. I had to keep `observe` function as it is right now, because it is used extensively in tests. Reviewed By: javache Differential Revision: D86449266 fbshipit-source-id: c7a2cffec760e697d8b5525e88997204b16fcd81 --- .../Libraries/LogBox/Data/LogBoxData.js | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/packages/react-native/Libraries/LogBox/Data/LogBoxData.js b/packages/react-native/Libraries/LogBox/Data/LogBoxData.js index 2ce92e06354..639e97af40d 100644 --- a/packages/react-native/Libraries/LogBox/Data/LogBoxData.js +++ b/packages/react-native/Libraries/LogBox/Data/LogBoxData.js @@ -412,6 +412,21 @@ export function observe(observer: Observer): Subscription { }; } +/** + * Same as observe(), but doesn't call notify observer sync at the time of subscription. + * Expected to be used only in LogBoxStateSubscription. + */ +function observeNext(observer: Observer): Subscription { + const subscription = {observer}; + observers.add(subscription); + + return { + unsubscribe(): void { + observers.delete(subscription); + }, + }; +} + type LogBoxStateSubscriptionProps = $ReadOnly<{}>; type LogBoxStateSubscriptionState = $ReadOnly<{ logs: LogBoxLogs, @@ -447,12 +462,11 @@ export function withSubscription( } _subscription: ?Subscription; + _updateStateOnMountTimeoutId: ?TimeoutID; state: LogBoxStateSubscriptionState = { - logs: new Set(), - isDisabled: false, hasError: false, - selectedLogIndex: -1, + ...getNextState(), }; render(): React.Node { @@ -472,12 +486,25 @@ export function withSubscription( } componentDidMount(): void { - this._subscription = observe(data => { + this._subscription = observeNext(data => { this.setState(data); }); + + /** + * This should cover the case when the state changes in between the first render and mount effect. + * We defer the state update to next task to avoid cascading update. + */ + this._updateStateOnMountTimeoutId = setTimeout(() => { + this._updateStateOnMountTimeoutId = null; + this.setState(getNextState()); + }, 0); } componentWillUnmount(): void { + if (this._updateStateOnMountTimeoutId != null) { + clearTimeout(this._updateStateOnMountTimeoutId); + } + if (this._subscription != null) { this._subscription.unsubscribe(); }