Skip to content

Commit 71c74d5

Browse files
committed
use(promise)
Adds experimental support to Fiber for unwrapping the value of a promise inside a component. It is not yet implemented for Server Components, but that is planned. If promise has already resolved, the value can be unwrapped "immediately" without showing a fallback. The trick we use to implement this is to yield to the main thread (literally suspending the work loop), wait for the microtask queue to drain, then check if the promise resolved in the meantime. If so, we can resume the last attempted fiber without unwinding the stack. This functionality was implemented in previous commits. Another feature is that the promises do not need to be cached between attempts. Because we assume idempotent execution of components, React will track the promises that were used during the previous attempt and reuse the result. You shouldn't rely on this property, but during initial render it mostly just works. Updates are trickier, though, because if you used an uncached promise, we have no way of knowing whether the underlying data has changed, so we have to unwrap the promise every time. It will still work, but it's inefficient and can lead to unnecessary fallbacks if it happens during a discrete update. When we implement this for Server Components, this will be less of an issue because there are no updates in that environment. However, it's still better for performance to cache data requests, so the same principles largely apply. The intention is that this will eventually be the only supported way to suspend on arbitrary promises. Throwing a promise directly will be deprecated.
1 parent 9377581 commit 71c74d5

11 files changed

+452
-30
lines changed

packages/react-reconciler/src/ReactFiberHooks.new.js

+76-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
ReactContext,
1515
StartTransitionOptions,
1616
Usable,
17+
Thenable,
1718
} from 'shared/ReactTypes';
1819
import type {Fiber, Dispatcher, HookType} from './ReactInternalTypes';
1920
import type {Lanes, Lane} from './ReactFiberLane.new';
@@ -121,6 +122,10 @@ import {
121122
} from './ReactFiberConcurrentUpdates.new';
122123
import {getTreeId} from './ReactFiberTreeContext.new';
123124
import {now} from './Scheduler';
125+
import {
126+
trackUsedThenable,
127+
getPreviouslyUsedThenableAtIndex,
128+
} from './ReactFiberWakeable.new';
124129

125130
const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;
126131

@@ -206,6 +211,9 @@ let didScheduleRenderPhaseUpdate: boolean = false;
206211
let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false;
207212
// Counts the number of useId hooks in this component.
208213
let localIdCounter: number = 0;
214+
// Counts number of `use`-d thenables
215+
let thenableIndexCounter: number = 0;
216+
209217
// Used for ids that are generated completely client-side (i.e. not during
210218
// hydration). This counter is global, so client ids are not stable across
211219
// render attempts.
@@ -404,6 +412,7 @@ export function renderWithHooks<Props, SecondArg>(
404412

405413
// didScheduleRenderPhaseUpdate = false;
406414
// localIdCounter = 0;
415+
// thenableIndexCounter = 0;
407416

408417
// TODO Warn if no hooks are used at all during mount, then some are used during update.
409418
// Currently we will identify the update render as a mount because memoizedState === null.
@@ -442,6 +451,7 @@ export function renderWithHooks<Props, SecondArg>(
442451
do {
443452
didScheduleRenderPhaseUpdateDuringThisPass = false;
444453
localIdCounter = 0;
454+
thenableIndexCounter = 0;
445455

446456
if (numberOfReRenders >= RE_RENDER_LIMIT) {
447457
throw new Error(
@@ -525,6 +535,7 @@ export function renderWithHooks<Props, SecondArg>(
525535
didScheduleRenderPhaseUpdate = false;
526536
// This is reset by checkDidRenderIdHook
527537
// localIdCounter = 0;
538+
thenableIndexCounter = 0;
528539

529540
if (didRenderTooFewHooks) {
530541
throw new Error(
@@ -632,6 +643,7 @@ export function resetHooksAfterThrow(): void {
632643

633644
didScheduleRenderPhaseUpdateDuringThisPass = false;
634645
localIdCounter = 0;
646+
thenableIndexCounter = 0;
635647
}
636648

637649
function mountWorkInProgressHook(): Hook {
@@ -724,7 +736,70 @@ function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
724736
}
725737

726738
function use<T>(usable: Usable<T>): T {
727-
throw new Error('Not implemented.');
739+
if (
740+
usable !== null &&
741+
typeof usable === 'object' &&
742+
typeof usable.then === 'function'
743+
) {
744+
// This is a thenable.
745+
const thenable: Thenable<T> = (usable: any);
746+
747+
// Track the position of the thenable within this fiber.
748+
const index = thenableIndexCounter;
749+
thenableIndexCounter += 1;
750+
751+
switch (thenable.status) {
752+
case 'fulfilled': {
753+
const fulfilledValue: T = thenable.value;
754+
return fulfilledValue;
755+
}
756+
case 'rejected': {
757+
const rejectedError = thenable.reason;
758+
throw rejectedError;
759+
}
760+
default: {
761+
const prevThenableAtIndex: Thenable<T> | null = getPreviouslyUsedThenableAtIndex(
762+
index,
763+
);
764+
if (prevThenableAtIndex !== null) {
765+
switch (prevThenableAtIndex.status) {
766+
case 'fulfilled': {
767+
const fulfilledValue: T = prevThenableAtIndex.value;
768+
return fulfilledValue;
769+
}
770+
case 'rejected': {
771+
const rejectedError: mixed = prevThenableAtIndex.reason;
772+
throw rejectedError;
773+
}
774+
default: {
775+
// The thenable still hasn't resolved. Suspend with the same
776+
// thenable as last time to avoid redundant listeners.
777+
throw prevThenableAtIndex;
778+
}
779+
}
780+
} else {
781+
// This is the first time something has been used at this index.
782+
// Stash the thenable at the current index so we can reuse it during
783+
// the next attempt.
784+
trackUsedThenable(thenable, index);
785+
786+
// Suspend.
787+
// TODO: Throwing here is an implementation detail that allows us to
788+
// unwind the call stack. But we shouldn't allow it to leak into
789+
// userspace. Throw an opaque placeholder value instead of the
790+
// actual thenable. If it doesn't get captured by the work loop, log
791+
// a warning, because that means something in userspace must have
792+
// caught it.
793+
throw thenable;
794+
}
795+
}
796+
}
797+
}
798+
799+
// TODO: Add support for Context
800+
801+
// eslint-disable-next-line react-internal/safe-string-coercion
802+
throw new Error('An unsupported type was passed to use(): ' + String(usable));
728803
}
729804

730805
function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {

packages/react-reconciler/src/ReactFiberHooks.old.js

+76-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
ReactContext,
1515
StartTransitionOptions,
1616
Usable,
17+
Thenable,
1718
} from 'shared/ReactTypes';
1819
import type {Fiber, Dispatcher, HookType} from './ReactInternalTypes';
1920
import type {Lanes, Lane} from './ReactFiberLane.old';
@@ -121,6 +122,10 @@ import {
121122
} from './ReactFiberConcurrentUpdates.old';
122123
import {getTreeId} from './ReactFiberTreeContext.old';
123124
import {now} from './Scheduler';
125+
import {
126+
trackUsedThenable,
127+
getPreviouslyUsedThenableAtIndex,
128+
} from './ReactFiberWakeable.old';
124129

125130
const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;
126131

@@ -206,6 +211,9 @@ let didScheduleRenderPhaseUpdate: boolean = false;
206211
let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false;
207212
// Counts the number of useId hooks in this component.
208213
let localIdCounter: number = 0;
214+
// Counts number of `use`-d thenables
215+
let thenableIndexCounter: number = 0;
216+
209217
// Used for ids that are generated completely client-side (i.e. not during
210218
// hydration). This counter is global, so client ids are not stable across
211219
// render attempts.
@@ -404,6 +412,7 @@ export function renderWithHooks<Props, SecondArg>(
404412

405413
// didScheduleRenderPhaseUpdate = false;
406414
// localIdCounter = 0;
415+
// thenableIndexCounter = 0;
407416

408417
// TODO Warn if no hooks are used at all during mount, then some are used during update.
409418
// Currently we will identify the update render as a mount because memoizedState === null.
@@ -442,6 +451,7 @@ export function renderWithHooks<Props, SecondArg>(
442451
do {
443452
didScheduleRenderPhaseUpdateDuringThisPass = false;
444453
localIdCounter = 0;
454+
thenableIndexCounter = 0;
445455

446456
if (numberOfReRenders >= RE_RENDER_LIMIT) {
447457
throw new Error(
@@ -525,6 +535,7 @@ export function renderWithHooks<Props, SecondArg>(
525535
didScheduleRenderPhaseUpdate = false;
526536
// This is reset by checkDidRenderIdHook
527537
// localIdCounter = 0;
538+
thenableIndexCounter = 0;
528539

529540
if (didRenderTooFewHooks) {
530541
throw new Error(
@@ -632,6 +643,7 @@ export function resetHooksAfterThrow(): void {
632643

633644
didScheduleRenderPhaseUpdateDuringThisPass = false;
634645
localIdCounter = 0;
646+
thenableIndexCounter = 0;
635647
}
636648

637649
function mountWorkInProgressHook(): Hook {
@@ -724,7 +736,70 @@ function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
724736
}
725737

726738
function use<T>(usable: Usable<T>): T {
727-
throw new Error('Not implemented.');
739+
if (
740+
usable !== null &&
741+
typeof usable === 'object' &&
742+
typeof usable.then === 'function'
743+
) {
744+
// This is a thenable.
745+
const thenable: Thenable<T> = (usable: any);
746+
747+
// Track the position of the thenable within this fiber.
748+
const index = thenableIndexCounter;
749+
thenableIndexCounter += 1;
750+
751+
switch (thenable.status) {
752+
case 'fulfilled': {
753+
const fulfilledValue: T = thenable.value;
754+
return fulfilledValue;
755+
}
756+
case 'rejected': {
757+
const rejectedError = thenable.reason;
758+
throw rejectedError;
759+
}
760+
default: {
761+
const prevThenableAtIndex: Thenable<T> | null = getPreviouslyUsedThenableAtIndex(
762+
index,
763+
);
764+
if (prevThenableAtIndex !== null) {
765+
switch (prevThenableAtIndex.status) {
766+
case 'fulfilled': {
767+
const fulfilledValue: T = prevThenableAtIndex.value;
768+
return fulfilledValue;
769+
}
770+
case 'rejected': {
771+
const rejectedError: mixed = prevThenableAtIndex.reason;
772+
throw rejectedError;
773+
}
774+
default: {
775+
// The thenable still hasn't resolved. Suspend with the same
776+
// thenable as last time to avoid redundant listeners.
777+
throw prevThenableAtIndex;
778+
}
779+
}
780+
} else {
781+
// This is the first time something has been used at this index.
782+
// Stash the thenable at the current index so we can reuse it during
783+
// the next attempt.
784+
trackUsedThenable(thenable, index);
785+
786+
// Suspend.
787+
// TODO: Throwing here is an implementation detail that allows us to
788+
// unwind the call stack. But we shouldn't allow it to leak into
789+
// userspace. Throw an opaque placeholder value instead of the
790+
// actual thenable. If it doesn't get captured by the work loop, log
791+
// a warning, because that means something in userspace must have
792+
// caught it.
793+
throw thenable;
794+
}
795+
}
796+
}
797+
}
798+
799+
// TODO: Add support for Context
800+
801+
// eslint-disable-next-line react-internal/safe-string-coercion
802+
throw new Error('An unsupported type was passed to use(): ' + String(usable));
728803
}
729804

730805
function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {

packages/react-reconciler/src/ReactFiberLane.new.js

+20-5
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,11 @@ export function markStarvedLanesAsExpired(
403403
// Iterate through the pending lanes and check if we've reached their
404404
// expiration time. If so, we'll assume the update is being starved and mark
405405
// it as expired to force it to finish.
406-
let lanes = pendingLanes;
406+
//
407+
// We exclude retry lanes because those must always be time sliced, in order
408+
// to unwrap uncached promises.
409+
// TODO: Write a test for this
410+
let lanes = pendingLanes & ~RetryLanes;
407411
while (lanes > 0) {
408412
const index = pickArbitraryLaneIndex(lanes);
409413
const lane = 1 << index;
@@ -436,11 +440,22 @@ export function getHighestPriorityPendingLanes(root: FiberRoot) {
436440
}
437441

438442
export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes {
439-
const everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
440-
if (everythingButOffscreen !== NoLanes) {
441-
return everythingButOffscreen;
443+
const pendingLanes = root.pendingLanes;
444+
445+
// Only includes lanes that include actual updates, not Suspense retries.
446+
// We omit Suspense retries because they must be allowed to yield to
447+
// microtasks, so that they can unwrap the value of an unmemoized promise.
448+
// (Unmemoized promises can only be unwrapped by yielding to the main thread.)
449+
//
450+
// We also omit OffscreenLane in this step because we only want to perform
451+
// prerendering work after all the normal rendering work has finished.
452+
const updateLanes = pendingLanes & ~(OffscreenLane | RetryLanes);
453+
if (updateLanes !== NoLanes) {
454+
return updateLanes;
442455
}
443-
if (everythingButOffscreen & OffscreenLane) {
456+
457+
// Prerendered lanes
458+
if (pendingLanes & OffscreenLane) {
444459
return OffscreenLane;
445460
}
446461
return NoLanes;

packages/react-reconciler/src/ReactFiberLane.old.js

+20-5
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,11 @@ export function markStarvedLanesAsExpired(
403403
// Iterate through the pending lanes and check if we've reached their
404404
// expiration time. If so, we'll assume the update is being starved and mark
405405
// it as expired to force it to finish.
406-
let lanes = pendingLanes;
406+
//
407+
// We exclude retry lanes because those must always be time sliced, in order
408+
// to unwrap uncached promises.
409+
// TODO: Write a test for this
410+
let lanes = pendingLanes & ~RetryLanes;
407411
while (lanes > 0) {
408412
const index = pickArbitraryLaneIndex(lanes);
409413
const lane = 1 << index;
@@ -436,11 +440,22 @@ export function getHighestPriorityPendingLanes(root: FiberRoot) {
436440
}
437441

438442
export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes {
439-
const everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
440-
if (everythingButOffscreen !== NoLanes) {
441-
return everythingButOffscreen;
443+
const pendingLanes = root.pendingLanes;
444+
445+
// Only includes lanes that include actual updates, not Suspense retries.
446+
// We omit Suspense retries because they must be allowed to yield to
447+
// microtasks, so that they can unwrap the value of an unmemoized promise.
448+
// (Unmemoized promises can only be unwrapped by yielding to the main thread.)
449+
//
450+
// We also omit OffscreenLane in this step because we only want to perform
451+
// prerendering work after all the normal rendering work has finished.
452+
const updateLanes = pendingLanes & ~(OffscreenLane | RetryLanes);
453+
if (updateLanes !== NoLanes) {
454+
return updateLanes;
442455
}
443-
if (everythingButOffscreen & OffscreenLane) {
456+
457+
// Prerendered lanes
458+
if (pendingLanes & OffscreenLane) {
444459
return OffscreenLane;
445460
}
446461
return NoLanes;

0 commit comments

Comments
 (0)