forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactUse-test.js
More file actions
2192 lines (1961 loc) · 68.7 KB
/
ReactUse-test.js
File metadata and controls
2192 lines (1961 loc) · 68.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactNoop;
let Scheduler;
let act;
let use;
let useDebugValue;
let useState;
let useTransition;
let useMemo;
let useEffect;
let Suspense;
let startTransition;
let pendingTextRequests;
let waitFor;
let waitForPaint;
let assertLog;
let waitForAll;
let waitForMicrotasks;
let assertConsoleErrorDev;
describe('ReactUse', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
use = React.use;
useDebugValue = React.useDebugValue;
useState = React.useState;
useTransition = React.useTransition;
useMemo = React.useMemo;
useEffect = React.useEffect;
Suspense = React.Suspense;
startTransition = React.startTransition;
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
assertLog = InternalTestUtils.assertLog;
waitForPaint = InternalTestUtils.waitForPaint;
waitFor = InternalTestUtils.waitFor;
waitForMicrotasks = InternalTestUtils.waitForMicrotasks;
assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
pendingTextRequests = new Map();
});
function resolveTextRequests(text) {
const requests = pendingTextRequests.get(text);
if (requests !== undefined) {
pendingTextRequests.delete(text);
requests.forEach(resolve => resolve(text));
}
}
function getAsyncText(text) {
// getAsyncText is completely uncached — it performs a new async operation
// every time it's called. During a transition, React should be able to
// unwrap it anyway.
Scheduler.log(`Async text requested [${text}]`);
return new Promise(resolve => {
const requests = pendingTextRequests.get(text);
if (requests !== undefined) {
requests.push(resolve);
pendingTextRequests.set(text, requests);
} else {
pendingTextRequests.set(text, [resolve]);
}
});
}
function Text({text}) {
Scheduler.log(text);
return text;
}
// This behavior was intentionally disabled to derisk the rollout of `use`.
// It changes the behavior of old, pre-`use` Suspense implementations. We may
// add this back; however, the plan is to migrate all existing Suspense code
// to `use`, so the extra code probably isn't worth it.
// @gate TODO
it('if suspended fiber is pinged in a microtask, retry immediately without unwinding the stack', async () => {
let fulfilled = false;
function Async() {
if (fulfilled) {
return <Text text="Async" />;
}
Scheduler.log('Suspend!');
throw Promise.resolve().then(() => {
Scheduler.log('Resolve in microtask');
fulfilled = true;
});
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Async />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertLog([
// React will yield when the async component suspends.
'Suspend!',
'Resolve in microtask',
// Finished rendering without unwinding the stack or preparing a fallback.
'Async',
]);
expect(root).toMatchRenderedOutput('Async');
});
it('if suspended fiber is pinged in a microtask, it does not block a transition from completing', async () => {
let fulfilled = false;
function Async() {
if (fulfilled) {
return <Text text="Async" />;
}
Scheduler.log('Suspend!');
throw Promise.resolve().then(() => {
Scheduler.log('Resolve in microtask');
fulfilled = true;
});
}
function App() {
return <Async />;
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertLog(['Suspend!', 'Resolve in microtask', 'Async']);
expect(root).toMatchRenderedOutput('Async');
});
it('does not infinite loop if already fulfilled thenable is thrown', async () => {
// An already fulfilled promise should never be thrown. Since it already
// fulfilled, we shouldn't bother trying to render again — doing so would
// likely lead to an infinite loop. This scenario should only happen if a
// userspace Suspense library makes an implementation mistake.
// Create an already fulfilled thenable
const thenable = {
then(ping) {},
status: 'fulfilled',
value: null,
};
let i = 0;
function Async() {
if (i++ > 50) {
throw new Error('Infinite loop detected');
}
Scheduler.log('Suspend!');
// This thenable should never be thrown because it already fulfilled.
// But if it is thrown, React should handle it gracefully.
throw thenable;
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Async />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog([
'Suspend!',
'Loading...',
// pre-warming
'Suspend!',
]);
expect(root).toMatchRenderedOutput('Loading...');
});
it('basic use(promise)', async () => {
const promiseA = Promise.resolve('A');
const promiseB = Promise.resolve('B');
const promiseC = Promise.resolve('C');
function Async() {
const text = use(promiseA) + use(promiseB) + use(promiseC);
return <Text text={text} />;
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Async />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertLog(['ABC']);
expect(root).toMatchRenderedOutput('ABC');
});
it("using a promise that's not cached between attempts", async () => {
function Async() {
const text =
use(Promise.resolve('A')) +
use(Promise.resolve('B')) +
use(Promise.resolve('C'));
return <Text text={text} />;
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Async />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertConsoleErrorDev([
'A component was suspended by an uncached promise. Creating ' +
'promises inside a Client Component or hook is not yet ' +
'supported, except via a Suspense-compatible library or framework.\n' +
' in App (at **)',
]);
assertLog(['ABC']);
expect(root).toMatchRenderedOutput('ABC');
});
it('using a rejected promise will throw', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
static getDerivedStateFromError(error) {
return {error};
}
render() {
if (this.state.error) {
return <Text text={this.state.error.message} />;
}
return this.props.children;
}
}
const promiseA = Promise.resolve('A');
const promiseB = Promise.reject(new Error('Oops!'));
const promiseC = Promise.resolve('C');
// Jest/Node will raise an unhandled rejected error unless we await this. It
// works fine in the browser, though.
await expect(promiseB).rejects.toThrow('Oops!');
function Async() {
const text = use(promiseA) + use(promiseB) + use(promiseC);
return <Text text={text} />;
}
function App() {
return (
<ErrorBoundary>
<Async />
</ErrorBoundary>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertLog(['Oops!', 'Oops!']);
});
it('use(promise) in multiple components', async () => {
// This tests that the state for tracking promises is reset per component.
const promiseA = Promise.resolve('A');
const promiseB = Promise.resolve('B');
const promiseC = Promise.resolve('C');
const promiseD = Promise.resolve('D');
function Child({prefix}) {
return <Text text={prefix + use(promiseC) + use(promiseD)} />;
}
function Parent() {
return <Child prefix={use(promiseA) + use(promiseB)} />;
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Parent />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertLog(['ABCD']);
expect(root).toMatchRenderedOutput('ABCD');
});
it('use(promise) in multiple sibling components', async () => {
// This tests that the state for tracking promises is reset per component.
const promiseA = {then: () => {}, status: 'pending', value: null};
const promiseB = {then: () => {}, status: 'pending', value: null};
const promiseC = {then: () => {}, status: 'fulfilled', value: 'C'};
const promiseD = {then: () => {}, status: 'fulfilled', value: 'D'};
function Sibling1({prefix}) {
return <Text text={use(promiseA) + use(promiseB)} />;
}
function Sibling2() {
return <Text text={use(promiseC) + use(promiseD)} />;
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Sibling1 />
<Sibling2 />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertLog(['Loading...']);
expect(root).toMatchRenderedOutput('Loading...');
});
it('erroring in the same component as an uncached promise does not result in an infinite loop', async () => {
class ErrorBoundary extends React.Component {
state = {error: null};
static getDerivedStateFromError(error) {
return {error};
}
render() {
if (this.state.error) {
return <Text text={'Caught an error: ' + this.state.error.message} />;
}
return this.props.children;
}
}
let i = 0;
function Async({
// Intentionally destrucutring a prop here so that our production error
// stack trick is triggered at the beginning of the function
prop,
}) {
if (i++ > 50) {
throw new Error('Infinite loop detected');
}
try {
use(Promise.resolve('Async'));
} catch (e) {
Scheduler.log('Suspend! [Async]');
throw e;
}
throw new Error('Oops!');
}
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<ErrorBoundary>
<Async />
</ErrorBoundary>
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
assertConsoleErrorDev([
'A component was suspended by an uncached promise. Creating ' +
'promises inside a Client Component or hook is not yet ' +
'supported, except via a Suspense-compatible library or framework.\n' +
' in App (at **)',
'A component was suspended by an uncached promise. Creating ' +
'promises inside a Client Component or hook is not yet ' +
'supported, except via a Suspense-compatible library or framework.\n' +
' in App (at **)',
]);
assertLog([
// First attempt. The uncached promise suspends.
'Suspend! [Async]',
// Because the promise already fulfilled, we're able to unwrap the value
// immediately in a microtask.
//
// Then we proceed to the rest of the component, which throws an error.
'Caught an error: Oops!',
// During the sync error recovery pass, the component suspends, because
// we were unable to unwrap the value of the promise.
'Suspend! [Async]',
'Loading...',
// Because the error recovery attempt suspended, React can't tell if the
// error was actually fixed, or it was masked by the suspended data.
// In this case, it wasn't actually fixed, so if we were to commit the
// suspended fallback, it would enter an endless error recovery loop.
//
// Instead, we disable error recovery for these lanes and start
// over again.
// This time, the error is thrown and we commit the result.
'Suspend! [Async]',
'Caught an error: Oops!',
]);
expect(root).toMatchRenderedOutput('Caught an error: Oops!');
});
it('basic use(context)', async () => {
const ContextA = React.createContext('');
const ContextB = React.createContext('B');
function Sync() {
const text = use(ContextA) + use(ContextB);
return text;
}
function App() {
return (
<ContextA.Provider value="A">
<Sync />
</ContextA.Provider>
);
}
const root = ReactNoop.createRoot();
root.render(<App />);
await waitForAll([]);
expect(root).toMatchRenderedOutput('AB');
});
it('interrupting while yielded should reset contexts', async () => {
let resolve;
const promise = new Promise(r => {
resolve = r;
});
const Context = React.createContext();
const lazy = React.lazy(() => {
return promise;
});
function ContextText() {
return <Text text={use(Context)} />;
}
function App({text}) {
return (
<div>
<Context.Provider value={text}>
{lazy}
<ContextText />
</Context.Provider>
</div>
);
}
const root = ReactNoop.createRoot();
startTransition(() => {
root.render(<App text="world" />);
});
await waitForPaint([]);
expect(root).toMatchRenderedOutput(null);
await resolve({default: <Text key="hi" text="Hello " />});
// Higher priority update that interrupts the first render
ReactNoop.flushSync(() => {
root.render(<App text="world!" />);
});
assertLog(['Hello ', 'world!']);
expect(root).toMatchRenderedOutput(<div>Hello world!</div>);
});
it('warns if use(promise) is wrapped with try/catch block', async () => {
function Async() {
try {
return <Text text={use(Promise.resolve('Async'))} />;
} catch (e) {
return <Text text="Fallback" />;
}
}
spyOnDev(console, 'error').mockImplementation(() => {});
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<Async />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<App />);
});
});
if (__DEV__) {
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error.mock.calls[0][0]).toContain(
'`use` was called from inside a try/catch block. This is not ' +
'allowed and can lead to unexpected behavior. To handle errors ' +
'triggered by `use`, wrap your component in a error boundary.',
);
console.error.mockRestore();
}
});
// @gate enableSuspendingDuringWorkLoop
it('during a transition, can unwrap async operations even if nothing is cached', async () => {
function App() {
return <Text text={use(getAsyncText('Async'))} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<Text text="(empty)" />
</Suspense>,
);
});
assertLog(['(empty)']);
expect(root).toMatchRenderedOutput('(empty)');
await act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
);
});
});
assertLog(['Async text requested [Async]']);
expect(root).toMatchRenderedOutput('(empty)');
await act(() => {
resolveTextRequests('Async');
});
assertLog(['Async text requested [Async]', 'Async']);
assertConsoleErrorDev([
'A component was suspended by an uncached promise. ' +
'Creating promises inside a Client Component or hook is not yet supported, ' +
'except via a Suspense-compatible library or framework.\n' +
' in App (at **)',
]);
expect(root).toMatchRenderedOutput('Async');
});
// @gate enableSuspendingDuringWorkLoop
it("does not prevent a Suspense fallback from showing if it's a new boundary, even during a transition", async () => {
function App() {
return <Text text={use(getAsyncText('Async'))} />;
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
);
});
});
// Even though the initial render was a transition, it shows a fallback.
assertLog(['Async text requested [Async]', 'Loading...']);
expect(root).toMatchRenderedOutput('Loading...');
// Resolve the original data
await act(() => {
resolveTextRequests('Async');
});
// During the retry, a fresh request is initiated. Now we must wait for this
// one to finish.
// TODO: This is awkward. Intuitively, you might expect for `act` to wait
// until the new request has finished loading. But if it's mock IO, as in
// this test, how would the developer be able to imperatively flush it if it
// wasn't initiated until the current `act` call? Can't think of a better
// strategy at the moment.
assertLog(['Async text requested [Async]']);
expect(root).toMatchRenderedOutput('Loading...');
// Flush the second request.
await act(() => {
resolveTextRequests('Async');
});
// This time it finishes because it was during a retry.
assertLog(['Async text requested [Async]', 'Async']);
assertConsoleErrorDev([
'A component was suspended by an uncached promise. ' +
'Creating promises inside a Client Component or hook is not yet supported, ' +
'except via a Suspense-compatible library or framework.\n' +
' in App (at **)',
]);
expect(root).toMatchRenderedOutput('Async');
});
// @gate enableSuspendingDuringWorkLoop
it('when waiting for data to resolve, a fresh update will trigger a restart', async () => {
function App() {
return <Text text={use(getAsyncText('Will never resolve'))} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<Suspense fallback={<Text text="Loading..." />} />);
});
await act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
);
});
});
assertLog(['Async text requested [Will never resolve]']);
await act(() => {
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<Text text="Something different" />
</Suspense>,
);
});
assertLog(['Something different']);
});
// @gate enableSuspendingDuringWorkLoop
it('when waiting for data to resolve, an update on a different root does not cause work to be dropped', async () => {
const promise = getAsyncText('Hi');
function App() {
return <Text text={use(promise)} />;
}
const root1 = ReactNoop.createRoot();
assertLog(['Async text requested [Hi]']);
await act(() => {
root1.render(<Suspense fallback={<Text text="Loading..." />} />);
});
// Start a transition on one root. It will suspend.
await act(() => {
startTransition(() => {
root1.render(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
);
});
});
assertLog([]);
// While we're waiting for the first root's data to resolve, a second
// root renders.
const root2 = ReactNoop.createRoot();
await act(() => {
root2.render('Do re mi');
});
expect(root2).toMatchRenderedOutput('Do re mi');
// Once the first root's data is ready, we should finish its transition.
await act(async () => {
await resolveTextRequests('Hi');
});
assertLog(['Hi']);
expect(root1).toMatchRenderedOutput('Hi');
});
// @gate enableSuspendingDuringWorkLoop
it('while suspended, hooks cannot be called (i.e. current dispatcher is unset correctly)', async () => {
function App() {
return <Text text={use(getAsyncText('Will never resolve'))} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<Suspense fallback={<Text text="Loading..." />} />);
});
await act(() => {
startTransition(() => {
root.render(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
);
});
});
assertLog(['Async text requested [Will never resolve]']);
// Calling a hook should error because we're oustide of a component.
expect(useState).toThrow(
'Invalid hook call. Hooks can only be called inside of the body of a ' +
'function component.',
);
});
it('unwraps thenable that fulfills synchronously without suspending', async () => {
function App() {
const thenable = {
then(resolve) {
// This thenable immediately resolves, synchronously, without waiting
// a microtask.
resolve('Hi');
},
};
try {
return <Text text={use(thenable)} />;
} catch {
throw new Error(
'`use` should not suspend because the thenable resolved synchronously.',
);
}
}
// Because the thenable resolves synchronously, we should be able to finish
// rendering synchronously, with no fallback.
const root = ReactNoop.createRoot();
ReactNoop.flushSync(() => {
root.render(<App />);
});
assertLog(['Hi']);
expect(root).toMatchRenderedOutput('Hi');
});
it('does not suspend indefinitely if an interleaved update was skipped', async () => {
function Child({childShouldSuspend}) {
return (
<Text
text={
childShouldSuspend
? use(getAsyncText('Will never resolve'))
: 'Child'
}
/>
);
}
let setChildShouldSuspend;
let setShowChild;
function Parent() {
const [showChild, _setShowChild] = useState(true);
setShowChild = _setShowChild;
const [childShouldSuspend, _setChildShouldSuspend] = useState(false);
setChildShouldSuspend = _setChildShouldSuspend;
Scheduler.log(
`childShouldSuspend: ${childShouldSuspend}, showChild: ${showChild}`,
);
return showChild ? (
<Child childShouldSuspend={childShouldSuspend} />
) : (
<Text text="(empty)" />
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<Parent />);
});
assertLog(['childShouldSuspend: false, showChild: true', 'Child']);
expect(root).toMatchRenderedOutput('Child');
await act(async () => {
// Perform an update that causes the app to suspend
startTransition(() => {
setChildShouldSuspend(true);
});
await waitFor(['childShouldSuspend: true, showChild: true']);
// While the update is in progress, schedule another update.
startTransition(() => {
setShowChild(false);
});
});
assertLog([
// Because the interleaved update is not higher priority than what we were
// already working on, it won't interrupt. The first update will continue,
// and will suspend.
'Async text requested [Will never resolve]',
// Instead of waiting for the promise to resolve, React notices there's
// another pending update that it hasn't tried yet. It will switch to
// rendering that instead.
//
// This time, the update hides the component that previous was suspending,
// so it finishes successfully.
'childShouldSuspend: false, showChild: false',
'(empty)',
// Finally, React attempts to render the first update again. It also
// finishes successfully, because it was rebased on top of the update that
// hid the suspended component.
// NOTE: These this render happened to not be entangled with the previous
// one. If they had been, this update would have been included in the
// previous render, and there wouldn't be an extra one here. This could
// change if we change our entanglement heurstics. Semantically, it
// shouldn't matter, though in general we try to work on transitions in
// parallel whenever possible. So even though in this particular case, the
// extra render is unnecessary, it's a nice property that it wasn't
// entangled with the other transition.
'childShouldSuspend: true, showChild: false',
'(empty)',
]);
expect(root).toMatchRenderedOutput('(empty)');
});
// @gate enableSuspendingDuringWorkLoop
it('when replaying a suspended component, reuses the hooks computed during the previous attempt (Memo)', async () => {
function ExcitingText({text}) {
// This computes the uppercased version of some text. Pretend it's an
// expensive operation that we want to reuse.
const uppercaseText = useMemo(() => {
Scheduler.log('Compute uppercase: ' + text);
return text.toUpperCase();
}, [text]);
// This adds an exclamation point to the text. Pretend it's an async
// operation that is sent to a service for processing.
const exclamatoryText = use(getAsyncText(uppercaseText + '!'));
// This surrounds the text with sparkle emojis. The purpose in this test
// is to show that you can suspend in the middle of a sequence of hooks
// without breaking anything.
const sparklingText = useMemo(() => {
Scheduler.log('Add sparkles: ' + exclamatoryText);
return `✨ ${exclamatoryText} ✨`;
}, [exclamatoryText]);
return <Text text={sparklingText} />;
}
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<ExcitingText text="Hello" />);
});
});
// Suspends while we wait for the async service to respond.
assertLog(['Compute uppercase: Hello', 'Async text requested [HELLO!]']);
expect(root).toMatchRenderedOutput(null);
// The data is received.
await act(() => {
resolveTextRequests('HELLO!');
});
assertConsoleErrorDev([
'A component was suspended by an uncached promise. ' +
'Creating promises inside a Client Component or hook is not yet supported, ' +
'except via a Suspense-compatible library or framework.\n' +
' in ExcitingText (at **)',
]);
assertLog([
// We shouldn't run the uppercase computation again, because we can reuse
// the computation from the previous attempt.
// 'Compute uppercase: Hello',
'Async text requested [HELLO!]',
'Add sparkles: HELLO!',
'✨ HELLO! ✨',
]);
});
// @gate enableSuspendingDuringWorkLoop
it('when replaying a suspended component, reuses the hooks computed during the previous attempt (State)', async () => {
let _setFruit;
let _setVegetable;
function Kitchen() {
const [fruit, setFruit] = useState('apple');
_setFruit = setFruit;
const usedFruit = use(getAsyncText(fruit));
const [vegetable, setVegetable] = useState('carrot');
_setVegetable = setVegetable;
return <Text text={usedFruit + ' ' + vegetable} />;
}
// Initial render.
const root = ReactNoop.createRoot();
await act(() => {
startTransition(() => {
root.render(<Kitchen />);
});
});
assertLog(['Async text requested [apple]']);
expect(root).toMatchRenderedOutput(null);
await act(() => {
resolveTextRequests('apple');
});
assertLog(['Async text requested [apple]', 'apple carrot']);
assertConsoleErrorDev([
'A component was suspended by an uncached promise. ' +
'Creating promises inside a Client Component or hook is not yet supported, ' +
'except via a Suspense-compatible library or framework.\n' +
' in Kitchen (at **)',
]);
expect(root).toMatchRenderedOutput('apple carrot');
// Update the state variable after the use().
await act(() => {
startTransition(() => {
_setVegetable('dill');
});
});
assertLog(['Async text requested [apple]']);
expect(root).toMatchRenderedOutput('apple carrot');
await act(() => {
resolveTextRequests('apple');
});
assertLog(['Async text requested [apple]', 'apple dill']);
assertConsoleErrorDev([
'A component was suspended by an uncached promise. ' +
'Creating promises inside a Client Component or hook is not yet supported, ' +
'except via a Suspense-compatible library or framework.\n' +
' in Kitchen (at **)',
]);
expect(root).toMatchRenderedOutput('apple dill');
// Update the state variable before the use(). The second state is maintained.
await act(() => {
startTransition(() => {
_setFruit('banana');
});
});
assertLog(['Async text requested [banana]']);
expect(root).toMatchRenderedOutput('apple dill');
await act(() => {
resolveTextRequests('banana');
});
assertLog(['Async text requested [banana]', 'banana dill']);
assertConsoleErrorDev([