Skip to content

Commit 6ff2bcd

Browse files
authored
Add unstable_flushSync export to react-native (#60491)
Exports `unstable_flushSync` from `react-native`, with the same semantics as [`flushSync` from `react-dom`](https://react.dev/reference/react-dom/flushSync). It's needed to read layout right after an update, or to apply updates from a `ResizeObserver` callback on the same frame as the size change. The renderer implementation landed in React (react/react#38475) and was synced in #60470. This change: - Re-exports `ReactFabric.flushSync` from `RendererImplementation`/`RendererProxy` and the jest-preset `RendererProxy` mock. - Adds a lazy `unstable_flushSync` getter to `index.js`, gated by a new `enableFlushSync` feature flag. The flag is off by default and isn't enabled in any OSS release stage yet (`ossReleaseStage: 'none'`); that will be flipped separately. When the flag is off, the export is `undefined`, so it's typed `?typeof flushSync`. [INTERNAL] [ADDED] - Add `unstable_flushSync` export to `react-native` behind the `enableFlushSync` feature flag (disabled by default) New Fantom tests in `flushSync-itest.js`, run with the flag on and off: - flushes updates before returning (vs. deferred without it); - opts out of transitions; - returns the callback's value, or `undefined` with no callback; - propagates errors from the callback and still flushes; - flushes pending discrete work when called with no callback, using a real discrete native event; - warns in DEV and defers the update when called during commit; - isn't exported when the flag is off. New `ResizeObserver` Fantom tests show that updates flushed with `unstable_flushSync` in the observer callback are mounted in the same layout pass, while updates without it land in a later one. ``` yarn fantom packages/react-native/Libraries/ReactNative/__tests__/flushSync-itest.js \ packages/react-native/src/private/webapis/resizeobserver/__tests__/ResizeObserver-itest.js yarn build-types && yarn test-generated-typescript # pass, no ReactNativeApi.d.ts change yarn flow # no new errors yarn eslint <changed files> # clean ``` Signed-off-by: Rubén Norte <rubennorte@meta.com>
1 parent 90724b8 commit 6ff2bcd

26 files changed

Lines changed: 504 additions & 98 deletions

‎packages/jest-preset/jest/mocks/RendererProxy.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const {
1717
dispatchCommand,
1818
findHostInstance_DEPRECATED,
1919
findNodeHandle,
20+
flushSync,
2021
getNodeFromInternalInstanceHandle,
2122
getPublicInstanceFromInternalInstanceHandle,
2223
getPublicInstanceFromRootTag,
@@ -32,6 +33,7 @@ export {
3233
dispatchCommand,
3334
findHostInstance_DEPRECATED,
3435
findNodeHandle,
36+
flushSync,
3537
getNodeFromInternalInstanceHandle,
3638
getPublicInstanceFromInternalInstanceHandle,
3739
getPublicInstanceFromRootTag,

‎packages/react-native/Libraries/ReactNative/RendererImplementation.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export const findNodeHandle: {
5050
componentOrHandle: ?(React.ElementRef<TElementType> | number),
5151
): ?number,
5252
}['findNodeHandle'] = ReactFabric.findNodeHandle;
53+
export const flushSync = ReactFabric.flushSync;
5354
export const sendAccessibilityEvent = ReactFabric.sendAccessibilityEvent;
5455
export const isChildPublicInstance = ReactFabric.isChildPublicInstance;
5556
export const getNodeFromInternalInstanceHandle =
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @fantom_flags enableFlushSync:*
8+
* @flow strict-local
9+
* @format
10+
*/
11+
12+
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
13+
14+
import type {HostInstance} from 'react-native';
15+
16+
import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags';
17+
import * as Fantom from '@react-native/fantom';
18+
import nullthrows from 'nullthrows';
19+
import * as React from 'react';
20+
import {createRef, startTransition, useLayoutEffect, useState} from 'react';
21+
import {View, unstable_flushSync as maybeFlushSync} from 'react-native';
22+
23+
let log: Array<string> = [];
24+
let setN: (n: number) => void = () => {};
25+
const counterRef = createRef<HostInstance>();
26+
27+
type CounterProps = {onPointerUp?: () => void};
28+
29+
function Counter({onPointerUp}: CounterProps): React.Node {
30+
const [n, _setN] = useState(0);
31+
setN = _setN;
32+
log.push(`render:${n}`);
33+
useLayoutEffect(() => {
34+
log.push(`layout:${n}`);
35+
}, [n]);
36+
return <View ref={counterRef} onPointerUp={onPointerUp} />;
37+
}
38+
39+
function renderCounter(props?: CounterProps): Fantom.Root {
40+
const root = Fantom.createRoot();
41+
Fantom.runTask(() => {
42+
root.render(<Counter {...props} />);
43+
});
44+
expect(log).toEqual(['render:0', 'layout:0']);
45+
log = [];
46+
return root;
47+
}
48+
49+
beforeEach(() => {
50+
log = [];
51+
});
52+
53+
(ReactNativeFeatureFlags.enableFlushSync() ? it.skip : it)(
54+
'is not exported when enableFlushSync is disabled',
55+
() => {
56+
expect(maybeFlushSync).toBe(undefined);
57+
},
58+
);
59+
60+
(ReactNativeFeatureFlags.enableFlushSync() ? describe : describe.skip)(
61+
'flushSync',
62+
() => {
63+
let flushSync: NonNullable<typeof maybeFlushSync>;
64+
65+
beforeEach(() => {
66+
flushSync = nullthrows(maybeFlushSync);
67+
});
68+
69+
it('is exported from react-native', () => {
70+
expect(typeof maybeFlushSync).toBe('function');
71+
});
72+
73+
it('flushes updates synchronously before returning', () => {
74+
renderCounter();
75+
76+
Fantom.runTask(() => {
77+
flushSync(() => setN(1));
78+
log.push('after');
79+
});
80+
81+
expect(log).toEqual(['render:1', 'layout:1', 'after']);
82+
});
83+
84+
it('without flushSync, updates are deferred', () => {
85+
renderCounter();
86+
87+
Fantom.runTask(() => {
88+
setN(1);
89+
log.push('after');
90+
});
91+
92+
expect(log).toEqual(['after', 'render:1', 'layout:1']);
93+
});
94+
95+
it('opts out of transitions', () => {
96+
renderCounter();
97+
98+
Fantom.runTask(() => {
99+
startTransition(() => {
100+
flushSync(() => setN(1));
101+
log.push('after');
102+
});
103+
});
104+
105+
expect(log).toEqual(['render:1', 'layout:1', 'after']);
106+
});
107+
108+
it("returns the callback's return value", () => {
109+
expect(flushSync(() => 42)).toBe(42);
110+
expect(flushSync()).toBe(undefined);
111+
});
112+
113+
it('propagates errors from the callback and still flushes updates', () => {
114+
renderCounter();
115+
116+
Fantom.runTask(() => {
117+
expect(() =>
118+
flushSync(() => {
119+
setN(1);
120+
throw new Error('boom');
121+
}),
122+
).toThrow('boom');
123+
log.push('after');
124+
});
125+
126+
expect(log).toEqual(['render:1', 'layout:1', 'after']);
127+
});
128+
129+
it('flushes pending sync work when called without a callback', () => {
130+
renderCounter({
131+
onPointerUp: () => {
132+
setN(1);
133+
flushSync();
134+
log.push('after');
135+
},
136+
});
137+
138+
Fantom.dispatchNativeEvent(
139+
nullthrows(counterRef.current),
140+
'onPointerUp',
141+
{x: 0, y: 0},
142+
{category: Fantom.NativeEventCategory.Discrete},
143+
);
144+
145+
expect(log).toEqual(['render:1', 'layout:1', 'after']);
146+
});
147+
148+
it('warns and defers the update when called during commit', () => {
149+
const originalConsoleError = console.error;
150+
const consoleErrorSpy = jest.fn();
151+
// $FlowFixMe[cannot-write]
152+
console.error = consoleErrorSpy;
153+
try {
154+
let didFlush = false;
155+
function App(): React.Node {
156+
useLayoutEffect(() => {
157+
if (!didFlush) {
158+
didFlush = true;
159+
flushSync(() => setN(1));
160+
log.push('after');
161+
}
162+
});
163+
return <Counter />;
164+
}
165+
166+
const root = Fantom.createRoot();
167+
Fantom.runTask(() => {
168+
root.render(<App />);
169+
});
170+
171+
expect(log).toEqual([
172+
'render:0',
173+
'layout:0',
174+
'after',
175+
'render:1',
176+
'layout:1',
177+
]);
178+
if (__DEV__) {
179+
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
180+
expect(consoleErrorSpy.mock.calls[0][0]).toBe(
181+
'flushSync was called from inside a lifecycle method. React ' +
182+
'cannot flush when React is already rendering. Consider moving ' +
183+
'this call to a scheduler task or micro task.',
184+
);
185+
} else {
186+
expect(consoleErrorSpy).not.toHaveBeenCalled();
187+
}
188+
} finally {
189+
// $FlowFixMe[cannot-write]
190+
console.error = originalConsoleError;
191+
}
192+
});
193+
},
194+
);

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<9a675a67a9ce5e7ca443dd319e2af91a>>
7+
* @generated SignedSource<<3a6a61e2cc2bf01a35ab5c3919462ad5>>
88
*/
99

1010
/**
@@ -198,6 +198,12 @@ public object ReactNativeFeatureFlags {
198198
@JvmStatic
199199
public fun enableFlexboxAutoMinSizeInStrictMode(): Boolean = accessor.enableFlexboxAutoMinSizeInStrictMode()
200200

201+
/**
202+
* Exposes `unstable_flushSync` from the `react-native` package, with the same semantics as `flushSync` from `react-dom`.
203+
*/
204+
@JvmStatic
205+
public fun enableFlushSync(): Boolean = accessor.enableFlushSync()
206+
201207
/**
202208
* When mount items are queued while MountItemDispatcher is already dispatching on Android (e.g. from a synchronous state update), dispatch them in the same frame instead of deferring them to the next one.
203209
*/

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<6b668cbb1ef60126d7e08b2d853b1262>>
7+
* @generated SignedSource<<fe927f4acf804e05b74dbe606e39746f>>
88
*/
99

1010
/**
@@ -48,6 +48,7 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces
4848
private var enableFabricCommitBranchingMergeOnMainThreadCache: Boolean? = null
4949
private var enableFabricLogsCache: Boolean? = null
5050
private var enableFlexboxAutoMinSizeInStrictModeCache: Boolean? = null
51+
private var enableFlushSyncCache: Boolean? = null
5152
private var enableFollowUpMountItemDispatchAndroidCache: Boolean? = null
5253
private var enableIOSCompressedTextFrameAdjustmentCache: Boolean? = null
5354
private var enableIOSTextBaselineOffsetPerLineCache: Boolean? = null
@@ -376,6 +377,15 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces
376377
return cached
377378
}
378379

380+
override fun enableFlushSync(): Boolean {
381+
var cached = enableFlushSyncCache
382+
if (cached == null) {
383+
cached = ReactNativeFeatureFlagsCxxInterop.enableFlushSync()
384+
enableFlushSyncCache = cached
385+
}
386+
return cached
387+
}
388+
379389
override fun enableFollowUpMountItemDispatchAndroid(): Boolean {
380390
var cached = enableFollowUpMountItemDispatchAndroidCache
381391
if (cached == null) {

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<0890a0b7979d00172b0a79abd94f6c3e>>
7+
* @generated SignedSource<<b58702a0f594f409c0d20fd497395fde>>
88
*/
99

1010
/**
@@ -84,6 +84,8 @@ public object ReactNativeFeatureFlagsCxxInterop {
8484

8585
@DoNotStrip @JvmStatic public external fun enableFlexboxAutoMinSizeInStrictMode(): Boolean
8686

87+
@DoNotStrip @JvmStatic public external fun enableFlushSync(): Boolean
88+
8789
@DoNotStrip @JvmStatic public external fun enableFollowUpMountItemDispatchAndroid(): Boolean
8890

8991
@DoNotStrip @JvmStatic public external fun enableIOSCompressedTextFrameAdjustment(): Boolean

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<3ca183dbeeb3fdeac98780267df9dff2>>
7+
* @generated SignedSource<<834b0e9533cbc775a1c12b86140d718d>>
88
*/
99

1010
/**
@@ -79,6 +79,8 @@ public open class ReactNativeFeatureFlagsDefaults : ReactNativeFeatureFlagsProvi
7979

8080
override fun enableFlexboxAutoMinSizeInStrictMode(): Boolean = false
8181

82+
override fun enableFlushSync(): Boolean = false
83+
8284
override fun enableFollowUpMountItemDispatchAndroid(): Boolean = false
8385

8486
override fun enableIOSCompressedTextFrameAdjustment(): Boolean = false

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<ba5e55492e7f521229dd62ac1274924e>>
7+
* @generated SignedSource<<15c65d4497fd9f36f8902efb2812b3b2>>
88
*/
99

1010
/**
@@ -52,6 +52,7 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc
5252
private var enableFabricCommitBranchingMergeOnMainThreadCache: Boolean? = null
5353
private var enableFabricLogsCache: Boolean? = null
5454
private var enableFlexboxAutoMinSizeInStrictModeCache: Boolean? = null
55+
private var enableFlushSyncCache: Boolean? = null
5556
private var enableFollowUpMountItemDispatchAndroidCache: Boolean? = null
5657
private var enableIOSCompressedTextFrameAdjustmentCache: Boolean? = null
5758
private var enableIOSTextBaselineOffsetPerLineCache: Boolean? = null
@@ -408,6 +409,16 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc
408409
return cached
409410
}
410411

412+
override fun enableFlushSync(): Boolean {
413+
var cached = enableFlushSyncCache
414+
if (cached == null) {
415+
cached = currentProvider.enableFlushSync()
416+
accessedFeatureFlags.add("enableFlushSync")
417+
enableFlushSyncCache = cached
418+
}
419+
return cached
420+
}
421+
411422
override fun enableFollowUpMountItemDispatchAndroid(): Boolean {
412423
var cached = enableFollowUpMountItemDispatchAndroidCache
413424
if (cached == null) {

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<8d21b1b7d2bd5c5fe3a111c0d411f742>>
7+
* @generated SignedSource<<89f683cb28a7d1ef52c86faa96f1107c>>
88
*/
99

1010
/**
@@ -79,6 +79,8 @@ public interface ReactNativeFeatureFlagsProvider {
7979

8080
@DoNotStrip public fun enableFlexboxAutoMinSizeInStrictMode(): Boolean
8181

82+
@DoNotStrip public fun enableFlushSync(): Boolean
83+
8284
@DoNotStrip public fun enableFollowUpMountItemDispatchAndroid(): Boolean
8385

8486
@DoNotStrip public fun enableIOSCompressedTextFrameAdjustment(): Boolean

0 commit comments

Comments
 (0)