Skip to content

Commit 9120f6c

Browse files
authored
Support sync thenables for lazy() (#14626)
* Support sync thenables for lazy() * Don't commit twice
1 parent b66e6e4 commit 9120f6c

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

packages/react-reconciler/src/ReactFiberLazyComponent.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export function readLazyComponentType<T>(lazyComponent: LazyComponent<T>): T {
4747
lazyComponent._status = Pending;
4848
const ctor = lazyComponent._ctor;
4949
const thenable = ctor();
50+
lazyComponent._result = thenable;
5051
thenable.then(
5152
moduleObject => {
5253
if (lazyComponent._status === Pending) {
@@ -73,7 +74,10 @@ export function readLazyComponentType<T>(lazyComponent: LazyComponent<T>): T {
7374
}
7475
},
7576
);
76-
lazyComponent._result = thenable;
77+
// Check if it resolved synchronously
78+
if (lazyComponent._status === Resolved) {
79+
return lazyComponent._result;
80+
}
7781
throw thenable;
7882
}
7983
}

packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js

+17
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,23 @@ describe('ReactLazy', () => {
6161
expect(root).toMatchRenderedOutput('Hi again');
6262
});
6363

64+
it('can resolve synchronously without suspending', async () => {
65+
const LazyText = lazy(() => ({
66+
then(cb) {
67+
cb({default: Text});
68+
},
69+
}));
70+
71+
const root = ReactTestRenderer.create(
72+
<Suspense fallback={<Text text="Loading..." />}>
73+
<LazyText text="Hi" />
74+
</Suspense>,
75+
);
76+
77+
expect(ReactTestRenderer).toHaveYielded(['Hi']);
78+
expect(root).toMatchRenderedOutput('Hi');
79+
});
80+
6481
it('multiple lazy components', async () => {
6582
function Foo() {
6683
return <Text text="Foo" />;

0 commit comments

Comments
 (0)