@samitouri / QOS-React-2 / commits / c2d6552079

Unify `use` and `renderDidSuspendDelayIfPossible` implementations (#25922)

When unwrapping a promise with `use`, we sometimes suspend the work loop from rendering anything else until the data has resolved. This is different from how Suspense works in the old throw-a-promise world, where rather than suspend rendering midway through the render phase, we prepare a fallback and block the commit at the end, if necessary; however, the logic for determining whether it's OK to block is the same. The implementation is only incidentally different because it happens in two different parts of the code. This means for `use`, we end up doing the same checks twice, which is wasteful in terms of computation, but also introduces a risk that the logic will accidentally diverge. This unifies the implementation by moving it into the SuspenseContext module. Most of the logic for deciding whether to suspend is already performed in the begin phase of SuspenseComponent, so it makes sense to store that information on the stack rather than recompute it on demand. The way I've chosen to model this is to track whether the work loop is rendering inside the "shell" of the tree. The shell is defined as the part of the tree that's visible in the current UI. Once we enter a new Suspense boundary (or a hidden Offscreen boundary, which acts a Suspense boundary), we're no longer in the shell. This is already how Suspense behavior was modeled in terms of UX, so using this concept directly in the implementation turns out to result in less code than before. For the most part, this is purely an internal refactor, though it does fix a bug in the `use` implementation related to nested Suspense boundaries. I wouldn't be surprised if it happens to fix other bugs that we haven't yet discovered, especially around Offscreen. I'll add more tests as I think of them.

Andrew Clark committed Jan 4, 2023 at 15:11 UTC c2d6552079178b36619f5dfd1ea39ae80b1d38b5
6 files changed +297 -132
packages/react-reconciler/src/ReactFiberCompleteWork.js
-21
@@ -126,7 +126,6 @@ import {
126 setShallowSuspenseListContext,
127 ForceSuspenseFallback,
128 setDefaultShallowSuspenseListContext,
129 - isBadSuspenseFallback,
129 } from './ReactFiberSuspenseContext';
130 import {popHiddenContext} from './ReactFiberHiddenContext';
131 import {findFirstSuspended} from './ReactFiberSuspenseComponent';
@@ -148,8 +147,6 @@ import {
147 upgradeHydrationErrorsToRecoverable,
148 } from './ReactFiberHydrationContext';
149 import {
151 - renderDidSuspend,
152 - renderDidSuspendDelayIfPossible,
150 renderHasNotSuspendedYet,
151 getRenderTargetTime,
152 getWorkInProgressTransitions,
@@ -1257,24 +1254,6 @@ function completeWork(
1254 if (nextDidTimeout) {
1255 const offscreenFiber: Fiber = (workInProgress.child: any);
1256 offscreenFiber.flags |= Visibility;
1260 -
1261 - // TODO: This will still suspend a synchronous tree if anything
1262 - // in the concurrent tree already suspended during this render.
1263 - // This is a known bug.
1264 - if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
1265 - // TODO: Move this back to throwException because this is too late
1266 - // if this is a large tree which is common for initial loads. We
1267 - // don't know if we should restart a render or not until we get
1268 - // this marker, and this is too late.
1269 - // If this render already had a ping or lower pri updates,
1270 - // and this is the first time we know we're going to suspend we
1271 - // should be able to immediately restart from within throwException.
1272 - if (isBadSuspenseFallback(current, newProps)) {
1273 - renderDidSuspendDelayIfPossible();
1274 - } else {
1275 - renderDidSuspend();
1276 - }
1277 - }
1257 }
1258 }
1259
packages/react-reconciler/src/ReactFiberSuspenseContext.js
+80 -70
@@ -9,12 +9,13 @@
9
10 import type {Fiber} from './ReactInternalTypes';
11 import type {StackCursor} from './ReactFiberStack';
12 -import type {SuspenseState, SuspenseProps} from './ReactFiberSuspenseComponent';
12 +import type {SuspenseProps, SuspenseState} from './ReactFiberSuspenseComponent';
13 +import type {OffscreenState} from './ReactFiberOffscreenComponent';
14
15 import {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags';
16 import {createCursor, push, pop} from './ReactFiberStack';
17 import {isCurrentTreeHidden} from './ReactFiberHiddenContext';
17 -import {SuspenseComponent, OffscreenComponent} from './ReactWorkTags';
18 +import {OffscreenComponent} from './ReactWorkTags';
19
20 // The Suspense handler is the boundary that should capture if something
21 // suspends, i.e. it's the nearest `catch` block on the stack.
@@ -22,81 +23,72 @@ const suspenseHandlerStackCursor: StackCursor<Fiber | null> = createCursor(
23 null,
24 );
25
25 -function shouldAvoidedBoundaryCapture(
26 - workInProgress: Fiber,
27 - handlerOnStack: Fiber,
28 - props: any,
29 -): boolean {
30 - if (enableSuspenseAvoidThisFallback) {
31 - // If the parent is already showing content, and we're not inside a hidden
32 - // tree, then we should show the avoided fallback.
33 - if (handlerOnStack.alternate !== null && !isCurrentTreeHidden()) {
34 - return true;
35 - }
36 -
37 - // If the handler on the stack is also an avoided boundary, then we should
38 - // favor this inner one.
39 - if (
40 - handlerOnStack.tag === SuspenseComponent &&
41 - handlerOnStack.memoizedProps.unstable_avoidThisFallback === true
42 - ) {
43 - return true;
44 - }
45 -
46 - // If this avoided boundary is dehydrated, then it should capture.
47 - const suspenseState: SuspenseState | null = workInProgress.memoizedState;
48 - if (suspenseState !== null && suspenseState.dehydrated !== null) {
49 - return true;
50 - }
51 - }
52 -
53 - // If none of those cases apply, then we should avoid this fallback and show
54 - // the outer one instead.
55 - return false;
56 -}
57 -
58 -export function isBadSuspenseFallback(
59 - current: Fiber | null,
60 - nextProps: SuspenseProps,
61 -): boolean {
62 - // Check if this is a "bad" fallback state or a good one. A bad fallback state
63 - // is one that we only show as a last resort; if this is a transition, we'll
64 - // block it from displaying, and wait for more data to arrive.
65 - if (current !== null) {
66 - const prevState: SuspenseState = current.memoizedState;
67 - const isShowingFallback = prevState !== null;
68 - if (!isShowingFallback && !isCurrentTreeHidden()) {
69 - // It's bad to switch to a fallback if content is already visible
70 - return true;
71 - }
72 - }
73 -
74 - if (
75 - enableSuspenseAvoidThisFallback &&
76 - nextProps.unstable_avoidThisFallback === true
77 - ) {
78 - // Experimental: Some fallbacks are always bad
79 - return true;
80 - }
81 -
82 - return false;
26 +// Represents the outermost boundary that is not visible in the current tree.
27 +// Everything above this is the "shell". When this is null, it means we're
28 +// rendering in the shell of the app. If it's non-null, it means we're rendering
29 +// deeper than the shell, inside a new tree that wasn't already visible.
30 +//
31 +// The main way we use this concept is to determine whether showing a fallback
32 +// would result in a desirable or undesirable loading state. Activing a fallback
33 +// in the shell is considered an undersirable loading state, because it would
34 +// mean hiding visible (albeit stale) content in the current tree — we prefer to
35 +// show the stale content, rather than switch to a fallback. But showing a
36 +// fallback in a new tree is fine, because there's no stale content to
37 +// prefer instead.
38 +let shellBoundary: Fiber | null = null;
39 +
40 +export function getShellBoundary(): Fiber | null {
41 + return shellBoundary;
42 }
43
44 export function pushPrimaryTreeSuspenseHandler(handler: Fiber): void {
86 - const props = handler.pendingProps;
87 - const handlerOnStack = suspenseHandlerStackCursor.current;
45 + // TODO: Pass as argument
46 + const current = handler.alternate;
47 + const props: SuspenseProps = handler.pendingProps;
48 +
49 + // Experimental feature: Some Suspense boundaries are marked as having an
50 + // undesirable fallback state. These have special behavior where we only
51 + // activate the fallback if there's no other boundary on the stack that we can
52 + // use instead.
53 if (
54 enableSuspenseAvoidThisFallback &&
55 props.unstable_avoidThisFallback === true &&
91 - handlerOnStack !== null &&
92 - !shouldAvoidedBoundaryCapture(handler, handlerOnStack, props)
56 + // If an avoided boundary is already visible, it behaves identically to
57 + // a regular Suspense boundary.
58 + (current === null || isCurrentTreeHidden())
59 ) {
94 - // This boundary should not capture if something suspends. Reuse the
95 - // existing handler on the stack.
96 - push(suspenseHandlerStackCursor, handlerOnStack, handler);
97 - } else {
98 - // Push this handler onto the stack.
99 - push(suspenseHandlerStackCursor, handler, handler);
60 + if (shellBoundary === null) {
61 + // We're rendering in the shell. There's no parent Suspense boundary that
62 + // can provide a desirable fallback state. We'll use this boundary.
63 + push(suspenseHandlerStackCursor, handler, handler);
64 +
65 + // However, because this is not a desirable fallback, the children are
66 + // still considered part of the shell. So we intentionally don't assign
67 + // to `shellBoundary`.
68 + } else {
69 + // There's already a parent Suspense boundary that can provide a desirable
70 + // fallback state. Prefer that one.
71 + const handlerOnStack = suspenseHandlerStackCursor.current;
72 + push(suspenseHandlerStackCursor, handlerOnStack, handler);
73 + }
74 + return;
75 + }
76 +
77 + // TODO: If the parent Suspense handler already suspended, there's no reason
78 + // to push a nested Suspense handler, because it will get replaced by the
79 + // outer fallback, anyway. Consider this as a future optimization.
80 + push(suspenseHandlerStackCursor, handler, handler);
81 + if (shellBoundary === null) {
82 + if (current === null || isCurrentTreeHidden()) {
83 + // This boundary is not visible in the current UI.
84 + shellBoundary = handler;
85 + } else {
86 + const prevState: SuspenseState = current.memoizedState;
87 + if (prevState !== null) {
88 + // This boundary is showing a fallback in the current UI.
89 + shellBoundary = handler;
90 + }
91 + }
92 }
93 }
94
@@ -110,6 +102,20 @@ export function pushFallbackTreeSuspenseHandler(fiber: Fiber): void {
102 export function pushOffscreenSuspenseHandler(fiber: Fiber): void {
103 if (fiber.tag === OffscreenComponent) {
104 push(suspenseHandlerStackCursor, fiber, fiber);
105 + if (shellBoundary !== null) {
106 + // A parent boundary is showing a fallback, so we've already rendered
107 + // deeper than the shell.
108 + } else {
109 + const current = fiber.alternate;
110 + if (current !== null) {
111 + const prevState: OffscreenState = current.memoizedState;
112 + if (prevState !== null) {
113 + // This is the first boundary in the stack that's already showing
114 + // a fallback. So everything outside is considered the shell.
115 + shellBoundary = fiber;
116 + }
117 + }
118 + }
119 } else {
120 // This is a LegacyHidden component.
121 reuseSuspenseHandlerOnStack(fiber);
@@ -126,6 +132,10 @@ export function getSuspenseHandler(): Fiber | null {
132
133 export function popSuspenseHandler(fiber: Fiber): void {
134 pop(suspenseHandlerStackCursor, fiber);
135 + if (shellBoundary === fiber) {
136 + // Popping back into the shell.
137 + shellBoundary = null;
138 + }
139 }
140
141 // SuspenseList context
packages/react-reconciler/src/ReactFiberThrow.js
+41 -2
@@ -49,7 +49,10 @@ import {
49 enqueueUpdate,
50 } from './ReactFiberClassUpdateQueue';
51 import {markFailedErrorBoundaryForHotReloading} from './ReactFiberHotReloading';
52 -import {getSuspenseHandler} from './ReactFiberSuspenseContext';
52 +import {
53 + getShellBoundary,
54 + getSuspenseHandler,
55 +} from './ReactFiberSuspenseContext';
56 import {
57 renderDidError,
58 renderDidSuspendDelayIfPossible,
@@ -58,6 +61,7 @@ import {
61 isAlreadyFailedLegacyErrorBoundary,
62 attachPingListener,
63 restorePendingUpdaters,
64 + renderDidSuspend,
65 } from './ReactFiberWorkLoop';
66 import {propagateParentContextChangesToDeferredTree} from './ReactFiberNewContext';
67 import {logCapturedError} from './ReactFiberErrorLogger';
@@ -349,11 +353,46 @@ function throwException(
353 }
354 }
355
352 - // Schedule the nearest Suspense to re-render the timed out view.
356 + // Mark the nearest Suspense boundary to switch to rendering a fallback.
357 const suspenseBoundary = getSuspenseHandler();
358 if (suspenseBoundary !== null) {
359 switch (suspenseBoundary.tag) {
360 case SuspenseComponent: {
361 + // If this suspense boundary is not already showing a fallback, mark
362 + // the in-progress render as suspended. We try to perform this logic
363 + // as soon as soon as possible during the render phase, so the work
364 + // loop can know things like whether it's OK to switch to other tasks,
365 + // or whether it can wait for data to resolve before continuing.
366 + // TODO: Most of these checks are already performed when entering a
367 + // Suspense boundary. We should track the information on the stack so
368 + // we don't have to recompute it on demand. This would also allow us
369 + // to unify with `use` which needs to perform this logic even sooner,
370 + // before `throwException` is called.
371 + if (sourceFiber.mode & ConcurrentMode) {
372 + if (getShellBoundary() === null) {
373 + // Suspended in the "shell" of the app. This is an undesirable
374 + // loading state. We should avoid committing this tree.
375 + renderDidSuspendDelayIfPossible();
376 + } else {
377 + // If we suspended deeper than the shell, we don't need to delay
378 + // the commmit. However, we still call renderDidSuspend if this is
379 + // a new boundary, to tell the work loop that a new fallback has
380 + // appeared during this render.
381 + // TODO: Theoretically we should be able to delete this branch.
382 + // It's currently used for two things: 1) to throttle the
383 + // appearance of successive loading states, and 2) in
384 + // SuspenseList, to determine whether the children include any
385 + // pending fallbacks. For 1, we should apply throttling to all
386 + // retries, not just ones that render an additional fallback. For
387 + // 2, we should check subtreeFlags instead. Then we can delete
388 + // this branch.
389 + const current = suspenseBoundary.alternate;
390 + if (current === null) {
391 + renderDidSuspend();
392 + }
393 + }
394 + }
395 +
396 suspenseBoundary.flags &= ~ForceClientRender;
397 markSuspenseBoundaryShouldCapture(
398 suspenseBoundary,
packages/react-reconciler/src/ReactFiberWorkLoop.js
+27 -31
@@ -12,7 +12,7 @@ import {REACT_STRICT_MODE_TYPE} from 'shared/ReactSymbols';
12 import type {Wakeable, Thenable} from 'shared/ReactTypes';
13 import type {Fiber, FiberRoot} from './ReactInternalTypes';
14 import type {Lanes, Lane} from './ReactFiberLane';
15 -import type {SuspenseProps, SuspenseState} from './ReactFiberSuspenseComponent';
15 +import type {SuspenseState} from './ReactFiberSuspenseComponent';
16 import type {FunctionComponentUpdateQueue} from './ReactFiberHooks';
17 import type {EventPriority} from './ReactEventPriorities';
18 import type {
@@ -276,7 +276,7 @@ import {
276 import {schedulePostPaintCallback} from './ReactPostPaintCallback';
277 import {
278 getSuspenseHandler,
279 - isBadSuspenseFallback,
279 + getShellBoundary,
280 } from './ReactFiberSuspenseContext';
281 import {resolveDefaultProps} from './ReactFiberLazyComponent';
282
@@ -1859,18 +1859,11 @@ function handleThrow(root, thrownValue): void {
1859 }
1860
1861 function shouldAttemptToSuspendUntilDataResolves() {
1862 - // TODO: We should be able to move the
1863 - // renderDidSuspend/renderDidSuspendDelayIfPossible logic into this function,
1864 - // instead of repeating it in the complete phase. Or something to that effect.
1865 -
1866 - if (includesOnlyRetries(workInProgressRootRenderLanes)) {
1867 - // We can always wait during a retry.
1868 - return true;
1869 - }
1870 -
1862 // Check if there are other pending updates that might possibly unblock this
1863 // component from suspending. This mirrors the check in
1864 // renderDidSuspendDelayIfPossible. We should attempt to unify them somehow.
1865 + // TODO: Consider unwinding immediately, using the
1866 + // SuspendedOnHydration mechanism.
1867 if (
1868 includesNonIdleWork(workInProgressRootSkippedLanes) ||
1869 includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes)
@@ -1883,27 +1876,24 @@ function shouldAttemptToSuspendUntilDataResolves() {
1876 // TODO: We should be able to remove the equivalent check in
1877 // finishConcurrentRender, and rely just on this one.
1878 if (includesOnlyTransitions(workInProgressRootRenderLanes)) {
1886 - const suspenseHandler = getSuspenseHandler();
1887 - if (suspenseHandler !== null && suspenseHandler.tag === SuspenseComponent) {
1888 - const currentSuspenseHandler = suspenseHandler.alternate;
1889 - const nextProps: SuspenseProps = suspenseHandler.memoizedProps;
1890 - if (isBadSuspenseFallback(currentSuspenseHandler, nextProps)) {
1891 - // The nearest Suspense boundary is already showing content. We should
1892 - // avoid replacing it with a fallback, and instead wait until the
1893 - // data finishes loading.
1894 - return true;
1895 - } else {
1896 - // This is not a bad fallback condition. We should show a fallback
1897 - // immediately instead of waiting for the data to resolve. This includes
1898 - // when suspending inside new trees.
1899 - return false;
1900 - }
1901 - }
1879 + // If we're rendering inside the "shell" of the app, it's better to suspend
1880 + // rendering and wait for the data to resolve. Otherwise, we should switch
1881 + // to a fallback and continue rendering.
1882 + return getShellBoundary() === null;
1883 + }
1884
1903 - // During a transition, if there is no Suspense boundary (i.e. suspending in
1904 - // the "shell" of an application), or if we're inside a hidden tree, then
1905 - // we should wait until the data finishes loading.
1906 - return true;
1885 + const handler = getSuspenseHandler();
1886 + if (handler === null) {
1887 + // TODO: We should support suspending in the case where there's no
1888 + // parent Suspense boundary, even outside a transition. Somehow. Otherwise,
1889 + // an uncached promise can fall into an infinite loop.
1890 + } else {
1891 + if (includesOnlyRetries(workInProgressRootRenderLanes)) {
1892 + // During a retry, we can suspend rendering if the nearest Suspense boundary
1893 + // is the boundary of the "shell", because we're guaranteed not to block
1894 + // any new content from appearing.
1895 + return handler === getShellBoundary();
1896 + }
1897 }
1898
1899 // For all other Lanes besides Transitions and Retries, we should not wait
@@ -1981,6 +1971,8 @@ export function renderDidSuspendDelayIfPossible(): void {
1971 // (inside this function), since by suspending at the end of the render
1972 // phase introduces a potential mistake where we suspend lanes that were
1973 // pinged or updated while we were rendering.
1974 + // TODO: Consider unwinding immediately, using the
1975 + // SuspendedOnHydration mechanism.
1976 markRootSuspended(workInProgressRoot, workInProgressRootRenderLanes);
1977 }
1978 }
@@ -2198,6 +2190,10 @@ function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
2190 }
2191 // The work loop is suspended on data. We should wait for it to
2192 // resolve before continuing to render.
2193 + // TODO: Handle the case where the promise resolves synchronously.
2194 + // Usually this is handled when we instrument the promise to add a
2195 + // `status` field, but if the promise already has a status, we won't
2196 + // have added a listener until right here.
2197 const onResolution = () => {
2198 ensureRootIsScheduled(root, now());
2199 };
packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.js
+4 -8
@@ -995,14 +995,10 @@ describe('ReactSuspenseWithNoopRenderer', () => {
995 expect(Scheduler).toFlushAndYieldThrough(['Suspend! [Async]', 'Sibling']);
996
997 await resolveText('Async');
998 - expect(Scheduler).toFlushAndYield([
999 - // We've now pinged the boundary but we don't know if we should restart yet,
1000 - // because we haven't completed the suspense boundary.
1001 - 'Loading...',
1002 - // Once we've completed the boundary we restarted.
1003 - 'Async',
1004 - 'Sibling',
1005 - ]);
998 +
999 + // Because we're already showing a fallback, interrupt the current render
1000 + // and restart immediately.
1001 + expect(Scheduler).toFlushAndYield(['Async', 'Sibling']);
1002 expect(root).toMatchRenderedOutput(
1003 <>
1004 <span prop="Async" />
packages/react-reconciler/src/__tests__/ReactThenable-test.js
+145
@@ -9,6 +9,7 @@ let useState;
9 let useMemo;
10 let Suspense;
11 let startTransition;
12 +let cache;
13 let pendingTextRequests;
14
15 describe('ReactThenable', () => {
@@ -24,6 +25,7 @@ describe('ReactThenable', () => {
25 useMemo = React.useMemo;
26 Suspense = React.Suspense;
27 startTransition = React.startTransition;
28 + cache = React.cache;
29
30 pendingTextRequests = new Map();
31 });
@@ -876,4 +878,147 @@ describe('ReactThenable', () => {
878 ]);
879 },
880 );
881 +
882 + // @gate enableUseHook
883 + test('load multiple nested Suspense boundaries', async () => {
884 + const getCachedAsyncText = cache(getAsyncText);
885 +
886 + function AsyncText({text}) {
887 + return <Text text={use(getCachedAsyncText(text))} />;
888 + }
889 +
890 + const root = ReactNoop.createRoot();
891 + await act(async () => {
892 + root.render(
893 + <Suspense fallback={<Text text="(Loading A...)" />}>
894 + <AsyncText text="A" />
895 + <Suspense fallback={<Text text="(Loading B...)" />}>
896 + <AsyncText text="B" />
897 + <Suspense fallback={<Text text="(Loading C...)" />}>
898 + <AsyncText text="C" />
899 + </Suspense>
900 + </Suspense>
901 + </Suspense>,
902 + );
903 + });
904 + expect(Scheduler).toHaveYielded([
905 + 'Async text requested [A]',
906 + 'Async text requested [B]',
907 + 'Async text requested [C]',
908 + '(Loading C...)',
909 + '(Loading B...)',
910 + '(Loading A...)',
911 + ]);
912 + expect(root).toMatchRenderedOutput('(Loading A...)');
913 +
914 + await act(async () => {
915 + resolveTextRequests('A');
916 + });
917 + expect(Scheduler).toHaveYielded(['A', '(Loading C...)', '(Loading B...)']);
918 + expect(root).toMatchRenderedOutput('A(Loading B...)');
919 +
920 + await act(async () => {
921 + resolveTextRequests('B');
922 + });
923 + expect(Scheduler).toHaveYielded(['B', '(Loading C...)']);
924 + expect(root).toMatchRenderedOutput('AB(Loading C...)');
925 +
926 + await act(async () => {
927 + resolveTextRequests('C');
928 + });
929 + expect(Scheduler).toHaveYielded(['C']);
930 + expect(root).toMatchRenderedOutput('ABC');
931 + });
932 +
933 + // @gate enableUseHook
934 + test('load multiple nested Suspense boundaries (uncached requests)', async () => {
935 + // This the same as the previous test, except the requests are not cached.
936 + // The tree should still eventually resolve, despite the
937 + // duplicate requests.
938 + function AsyncText({text}) {
939 + // This initiates a new request on each render.
940 + return <Text text={use(getAsyncText(text))} />;
941 + }
942 +
943 + const root = ReactNoop.createRoot();
944 + await act(async () => {
945 + root.render(
946 + <Suspense fallback={<Text text="(Loading A...)" />}>
947 + <AsyncText text="A" />
948 + <Suspense fallback={<Text text="(Loading B...)" />}>
949 + <AsyncText text="B" />
950 + <Suspense fallback={<Text text="(Loading C...)" />}>
951 + <AsyncText text="C" />
952 + </Suspense>
953 + </Suspense>
954 + </Suspense>,
955 + );
956 + });
957 + expect(Scheduler).toHaveYielded([
958 + 'Async text requested [A]',
959 + 'Async text requested [B]',
960 + 'Async text requested [C]',
961 + '(Loading C...)',
962 + '(Loading B...)',
963 + '(Loading A...)',
964 + ]);
965 + expect(root).toMatchRenderedOutput('(Loading A...)');
966 +
967 + await act(async () => {
968 + resolveTextRequests('A');
969 + });
970 + expect(Scheduler).toHaveYielded(['Async text requested [A]']);
971 + expect(root).toMatchRenderedOutput('(Loading A...)');
972 +
973 + await act(async () => {
974 + resolveTextRequests('A');
975 + });
976 + expect(Scheduler).toHaveYielded([
977 + // React suspends until A finishes loading.
978 + 'Async text requested [A]',
979 + 'A',
980 +
981 + // Now React can continue rendering the rest of the tree.
982 +
983 + // React does not suspend on the inner requests, because that would
984 + // block A from appearing. Instead it shows a fallback.
985 + 'Async text requested [B]',
986 + 'Async text requested [C]',
987 + '(Loading C...)',
988 + '(Loading B...)',
989 + ]);
990 + expect(root).toMatchRenderedOutput('A(Loading B...)');
991 +
992 + await act(async () => {
993 + resolveTextRequests('B');
994 + });
995 + expect(Scheduler).toHaveYielded(['Async text requested [B]']);
996 + expect(root).toMatchRenderedOutput('A(Loading B...)');
997 +
998 + await act(async () => {
999 + resolveTextRequests('B');
1000 + });
1001 + expect(Scheduler).toHaveYielded([
1002 + // React suspends until B finishes loading.
1003 + 'Async text requested [B]',
1004 + 'B',
1005 +
1006 + // React does not suspend on C, because that would block B from appearing.
1007 + 'Async text requested [C]',
1008 + '(Loading C...)',
1009 + ]);
1010 + expect(root).toMatchRenderedOutput('AB(Loading C...)');
1011 +
1012 + await act(async () => {
1013 + resolveTextRequests('C');
1014 + });
1015 + expect(Scheduler).toHaveYielded(['Async text requested [C]']);
1016 + expect(root).toMatchRenderedOutput('AB(Loading C...)');
1017 +
1018 + await act(async () => {
1019 + resolveTextRequests('C');
1020 + });
1021 + expect(Scheduler).toHaveYielded(['Async text requested [C]', 'C']);
1022 + expect(root).toMatchRenderedOutput('ABC');
1023 + });
1024 });