Skip to content

Commit

Permalink
use(promise)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
acdlite committed Aug 12, 2022
1 parent 07313db commit 5ea4693
Show file tree
Hide file tree
Showing 9 changed files with 385 additions and 28 deletions.
96 changes: 95 additions & 1 deletion packages/react-reconciler/src/ReactFiberHooks.new.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import type {
ReactContext,
StartTransitionOptions,
Usable,
Thenable,
PendingThenable,
FulfilledThenable,
RejectedThenable,
} from 'shared/ReactTypes';
import type {Fiber, Dispatcher, HookType} from './ReactInternalTypes';
import type {Lanes, Lane} from './ReactFiberLane.new';
Expand Down Expand Up @@ -121,6 +125,10 @@ import {
} from './ReactFiberConcurrentUpdates.new';
import {getTreeId} from './ReactFiberTreeContext.new';
import {now} from './Scheduler';
import {
trackSuspendedThenable,
getSuspendedThenable,
} from './ReactFiberWakeable.new';

const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;

Expand Down Expand Up @@ -206,6 +214,9 @@ let didScheduleRenderPhaseUpdate: boolean = false;
let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false;
// Counts the number of useId hooks in this component.
let localIdCounter: number = 0;
// Counts number of `use`-d thenables
let thenableIndexCounter: number = 0;

// Used for ids that are generated completely client-side (i.e. not during
// hydration). This counter is global, so client ids are not stable across
// render attempts.
Expand Down Expand Up @@ -404,6 +415,7 @@ export function renderWithHooks<Props, SecondArg>(

// didScheduleRenderPhaseUpdate = false;
// localIdCounter = 0;
// thenableIndexCounter = 0;

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

if (numberOfReRenders >= RE_RENDER_LIMIT) {
throw new Error(
Expand Down Expand Up @@ -525,6 +538,7 @@ export function renderWithHooks<Props, SecondArg>(
didScheduleRenderPhaseUpdate = false;
// This is reset by checkDidRenderIdHook
// localIdCounter = 0;
thenableIndexCounter = 0;

if (didRenderTooFewHooks) {
throw new Error(
Expand Down Expand Up @@ -632,6 +646,7 @@ export function resetHooksAfterThrow(): void {

didScheduleRenderPhaseUpdateDuringThisPass = false;
localIdCounter = 0;
thenableIndexCounter = 0;
}

function mountWorkInProgressHook(): Hook {
Expand Down Expand Up @@ -724,7 +739,86 @@ function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
}

function use<T>(usable: Usable<T>): T {
throw new Error('Not implemented.');
if (
usable !== null &&
typeof usable === 'object' &&
typeof usable.then === 'function'
) {
// This is a thenable.
const thenable: Thenable<T> = (usable: any);

// Track the position of the thenable within this fiber.
const index = thenableIndexCounter;
thenableIndexCounter += 1;

switch (thenable.status) {
case 'fulfilled': {
const fulfilledValue: T = thenable.value;
return fulfilledValue;
}
case 'rejected': {
const rejectedError = thenable.reason;
throw rejectedError;
}
default: {
const prevThenableAtIndex: Thenable<T> | null = getSuspendedThenable(
index,
);
if (prevThenableAtIndex !== null) {
switch (prevThenableAtIndex.status) {
case 'fulfilled': {
const fulfilledValue: T = prevThenableAtIndex.value;
return fulfilledValue;
}
case 'rejected': {
const rejectedError: mixed = prevThenableAtIndex.reason;
throw rejectedError;
}
default: {
// The thenable still hasn't resolved. Suspend with the same
// thenable as last time to avoid redundant listeners.
throw prevThenableAtIndex;
}
}
} else {
// This is the first time something has been used at this index.
// Stash the thenable at the current index so we can reuse it during
// the next attempt.
trackSuspendedThenable(thenable, index);

// Assume that if the status is `pending`, there's already a listener
// that will set it to `fulfilled` or `rejected`.
// TODO: We could do this in `pingSuspendedRoot` instead.
if (thenable.status !== 'pending') {
const pendingThenable: PendingThenable<T> = (thenable: any);
pendingThenable.status = 'pending';
pendingThenable.then(
fulfilledValue => {
if (thenable.status === 'pending') {
const fulfilledThenable: FulfilledThenable<T> = (thenable: any);
fulfilledThenable.status = 'fulfilled';
fulfilledThenable.value = fulfilledValue;
}
},
(error: mixed) => {
if (thenable.status === 'pending') {
const rejectedThenable: RejectedThenable<T> = (thenable: any);
rejectedThenable.status = 'rejected';
rejectedThenable.reason = error;
}
},
);
}
throw thenable;
}
}
}
}

// TODO: Add support for Context

// eslint-disable-next-line react-internal/safe-string-coercion
throw new Error('An unsupported type was passed to use(): ' + String(usable));
}

function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
Expand Down
96 changes: 95 additions & 1 deletion packages/react-reconciler/src/ReactFiberHooks.old.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import type {
ReactContext,
StartTransitionOptions,
Usable,
Thenable,
PendingThenable,
FulfilledThenable,
RejectedThenable,
} from 'shared/ReactTypes';
import type {Fiber, Dispatcher, HookType} from './ReactInternalTypes';
import type {Lanes, Lane} from './ReactFiberLane.old';
Expand Down Expand Up @@ -121,6 +125,10 @@ import {
} from './ReactFiberConcurrentUpdates.old';
import {getTreeId} from './ReactFiberTreeContext.old';
import {now} from './Scheduler';
import {
trackSuspendedThenable,
getSuspendedThenable,
} from './ReactFiberWakeable.old';

const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals;

Expand Down Expand Up @@ -206,6 +214,9 @@ let didScheduleRenderPhaseUpdate: boolean = false;
let didScheduleRenderPhaseUpdateDuringThisPass: boolean = false;
// Counts the number of useId hooks in this component.
let localIdCounter: number = 0;
// Counts number of `use`-d thenables
let thenableIndexCounter: number = 0;

// Used for ids that are generated completely client-side (i.e. not during
// hydration). This counter is global, so client ids are not stable across
// render attempts.
Expand Down Expand Up @@ -404,6 +415,7 @@ export function renderWithHooks<Props, SecondArg>(

// didScheduleRenderPhaseUpdate = false;
// localIdCounter = 0;
// thenableIndexCounter = 0;

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

if (numberOfReRenders >= RE_RENDER_LIMIT) {
throw new Error(
Expand Down Expand Up @@ -525,6 +538,7 @@ export function renderWithHooks<Props, SecondArg>(
didScheduleRenderPhaseUpdate = false;
// This is reset by checkDidRenderIdHook
// localIdCounter = 0;
thenableIndexCounter = 0;

if (didRenderTooFewHooks) {
throw new Error(
Expand Down Expand Up @@ -632,6 +646,7 @@ export function resetHooksAfterThrow(): void {

didScheduleRenderPhaseUpdateDuringThisPass = false;
localIdCounter = 0;
thenableIndexCounter = 0;
}

function mountWorkInProgressHook(): Hook {
Expand Down Expand Up @@ -724,7 +739,86 @@ function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
}

function use<T>(usable: Usable<T>): T {
throw new Error('Not implemented.');
if (
usable !== null &&
typeof usable === 'object' &&
typeof usable.then === 'function'
) {
// This is a thenable.
const thenable: Thenable<T> = (usable: any);

// Track the position of the thenable within this fiber.
const index = thenableIndexCounter;
thenableIndexCounter += 1;

switch (thenable.status) {
case 'fulfilled': {
const fulfilledValue: T = thenable.value;
return fulfilledValue;
}
case 'rejected': {
const rejectedError = thenable.reason;
throw rejectedError;
}
default: {
const prevThenableAtIndex: Thenable<T> | null = getSuspendedThenable(
index,
);
if (prevThenableAtIndex !== null) {
switch (prevThenableAtIndex.status) {
case 'fulfilled': {
const fulfilledValue: T = prevThenableAtIndex.value;
return fulfilledValue;
}
case 'rejected': {
const rejectedError: mixed = prevThenableAtIndex.reason;
throw rejectedError;
}
default: {
// The thenable still hasn't resolved. Suspend with the same
// thenable as last time to avoid redundant listeners.
throw prevThenableAtIndex;
}
}
} else {
// This is the first time something has been used at this index.
// Stash the thenable at the current index so we can reuse it during
// the next attempt.
trackSuspendedThenable(thenable, index);

// Assume that if the status is `pending`, there's already a listener
// that will set it to `fulfilled` or `rejected`.
// TODO: We could do this in `pingSuspendedRoot` instead.
if (thenable.status !== 'pending') {
const pendingThenable: PendingThenable<T> = (thenable: any);
pendingThenable.status = 'pending';
pendingThenable.then(
fulfilledValue => {
if (thenable.status === 'pending') {
const fulfilledThenable: FulfilledThenable<T> = (thenable: any);
fulfilledThenable.status = 'fulfilled';
fulfilledThenable.value = fulfilledValue;
}
},
(error: mixed) => {
if (thenable.status === 'pending') {
const rejectedThenable: RejectedThenable<T> = (thenable: any);
rejectedThenable.status = 'rejected';
rejectedThenable.reason = error;
}
},
);
}
throw thenable;
}
}
}
}

// TODO: Add support for Context

// eslint-disable-next-line react-internal/safe-string-coercion
throw new Error('An unsupported type was passed to use(): ' + String(usable));
}

function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
Expand Down
40 changes: 37 additions & 3 deletions packages/react-reconciler/src/ReactFiberWakeable.new.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,28 @@
* @flow
*/

import type {Wakeable} from 'shared/ReactTypes';
import type {Wakeable, Thenable} from 'shared/ReactTypes';

let suspendedWakeable: Wakeable | null = null;
let wasPinged = false;
let adHocSuspendCount: number = 0;

let suspendedThenables: Array<Thenable<any> | void> | null = null;
let lastUsedThenable: Thenable<any> | null = null;

const MAX_AD_HOC_SUSPEND_COUNT = 50;

export function suspendedWakeableWasPinged() {
return wasPinged;
}

export function trackSuspendedWakeable(wakeable: Wakeable) {
adHocSuspendCount++;
if (wakeable !== lastUsedThenable) {
// If this wakeable was not just `use`-d, it must be an ad hoc wakeable
// that was thrown by an older Suspense implementation. Keep a count of
// these so that we can detect an infinite ping loop.
adHocSuspendCount++;
}
suspendedWakeable = wakeable;
}

Expand All @@ -35,10 +43,15 @@ export function attemptToPingSuspendedWakeable(wakeable: Wakeable) {
return false;
}

export function resetWakeableState() {
export function resetWakeableStateAfterEachAttempt() {
suspendedWakeable = null;
wasPinged = false;
adHocSuspendCount = 0;
lastUsedThenable = null;
}

export function resetThenableStateOnCompletion() {
suspendedThenables = null;
}

export function throwIfInfinitePingLoopDetected() {
Expand All @@ -48,3 +61,24 @@ export function throwIfInfinitePingLoopDetected() {
// the render phase so that it gets the component stack.
}
}

export function trackSuspendedThenable<T>(
thenable: Thenable<T>,
index: number,
) {
if (suspendedThenables === null) {
suspendedThenables = [];
}
suspendedThenables[index] = thenable;
lastUsedThenable = thenable;
}

export function getSuspendedThenable<T>(index: number): Thenable<T> | null {
if (suspendedThenables !== null) {
const thenable = suspendedThenables[index];
if (thenable !== undefined) {
return thenable;
}
}
return null;
}
Loading

0 comments on commit 5ea4693

Please sign in to comment.