mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
Allow suspending in the shell during hydration (#23304)
* Allow suspending in the shell during hydration Builds on behavior added in #23267. Initial hydration should be allowed to suspend in the shell. In practice, this happens because the code for the outer shell hasn't loaded yet. Currently if you try to do this, it errors because it expects there to be a parent Suspense boundary, because without a fallback we can't produce a consistent tree. However, for non-sync updates, we don't need to produce a consistent tree immediately — we can delay the commit until the data resolves. In #23267, I added support for suspending without a parent boundary if the update was wrapped with `startTransition`. Here, I've expanded this to include hydration, too. I wonder if we should expand this even further to include all non-sync/ discrete updates. * Allow suspending in shell for all non-sync updates Instead of erroring, we can delay the commit. The only time we'll continue to error when there's no parent Suspense boundary is during sync/discrete updates, because those are expected to produce a complete tree synchronously to maintain consistency with external state.
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its 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
|
||||
*/
|
||||
|
||||
let JSDOM;
|
||||
let React;
|
||||
let ReactDOM;
|
||||
let Scheduler;
|
||||
let clientAct;
|
||||
let ReactDOMFizzServer;
|
||||
let Stream;
|
||||
let document;
|
||||
let writable;
|
||||
let container;
|
||||
let buffer = '';
|
||||
let hasErrored = false;
|
||||
let fatalError = undefined;
|
||||
let textCache;
|
||||
|
||||
describe('ReactDOMFizzShellHydration', () => {
|
||||
beforeEach(() => {
|
||||
jest.resetModules();
|
||||
JSDOM = require('jsdom').JSDOM;
|
||||
React = require('react');
|
||||
ReactDOM = require('react-dom');
|
||||
Scheduler = require('scheduler');
|
||||
clientAct = require('jest-react').act;
|
||||
ReactDOMFizzServer = require('react-dom/server');
|
||||
Stream = require('stream');
|
||||
|
||||
textCache = new Map();
|
||||
|
||||
// Test Environment
|
||||
const jsdom = new JSDOM(
|
||||
'<!DOCTYPE html><html><head></head><body><div id="container">',
|
||||
{
|
||||
runScripts: 'dangerously',
|
||||
},
|
||||
);
|
||||
document = jsdom.window.document;
|
||||
container = document.getElementById('container');
|
||||
|
||||
buffer = '';
|
||||
hasErrored = false;
|
||||
|
||||
writable = new Stream.PassThrough();
|
||||
writable.setEncoding('utf8');
|
||||
writable.on('data', chunk => {
|
||||
buffer += chunk;
|
||||
});
|
||||
writable.on('error', error => {
|
||||
hasErrored = true;
|
||||
fatalError = error;
|
||||
});
|
||||
});
|
||||
|
||||
async function serverAct(callback) {
|
||||
await callback();
|
||||
// Await one turn around the event loop.
|
||||
// This assumes that we'll flush everything we have so far.
|
||||
await new Promise(resolve => {
|
||||
setImmediate(resolve);
|
||||
});
|
||||
if (hasErrored) {
|
||||
throw fatalError;
|
||||
}
|
||||
// JSDOM doesn't support stream HTML parser so we need to give it a proper fragment.
|
||||
// We also want to execute any scripts that are embedded.
|
||||
// We assume that we have now received a proper fragment of HTML.
|
||||
const bufferedContent = buffer;
|
||||
buffer = '';
|
||||
const fakeBody = document.createElement('body');
|
||||
fakeBody.innerHTML = bufferedContent;
|
||||
while (fakeBody.firstChild) {
|
||||
const node = fakeBody.firstChild;
|
||||
if (node.nodeName === 'SCRIPT') {
|
||||
const script = document.createElement('script');
|
||||
script.textContent = node.textContent;
|
||||
fakeBody.removeChild(node);
|
||||
container.appendChild(script);
|
||||
} else {
|
||||
container.appendChild(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resolveText(text) {
|
||||
const record = textCache.get(text);
|
||||
if (record === undefined) {
|
||||
const newRecord = {
|
||||
status: 'resolved',
|
||||
value: text,
|
||||
};
|
||||
textCache.set(text, newRecord);
|
||||
} else if (record.status === 'pending') {
|
||||
const thenable = record.value;
|
||||
record.status = 'resolved';
|
||||
record.value = text;
|
||||
thenable.pings.forEach(t => t());
|
||||
}
|
||||
}
|
||||
|
||||
function readText(text) {
|
||||
const record = textCache.get(text);
|
||||
if (record !== undefined) {
|
||||
switch (record.status) {
|
||||
case 'pending':
|
||||
throw record.value;
|
||||
case 'rejected':
|
||||
throw record.value;
|
||||
case 'resolved':
|
||||
return record.value;
|
||||
}
|
||||
} else {
|
||||
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
|
||||
|
||||
const thenable = {
|
||||
pings: [],
|
||||
then(resolve) {
|
||||
if (newRecord.status === 'pending') {
|
||||
thenable.pings.push(resolve);
|
||||
} else {
|
||||
Promise.resolve().then(() => resolve(newRecord.value));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const newRecord = {
|
||||
status: 'pending',
|
||||
value: thenable,
|
||||
};
|
||||
textCache.set(text, newRecord);
|
||||
|
||||
throw thenable;
|
||||
}
|
||||
}
|
||||
|
||||
// function Text({text}) {
|
||||
// Scheduler.unstable_yieldValue(text);
|
||||
// return text;
|
||||
// }
|
||||
|
||||
function AsyncText({text}) {
|
||||
readText(text);
|
||||
Scheduler.unstable_yieldValue(text);
|
||||
return text;
|
||||
}
|
||||
|
||||
function resetTextCache() {
|
||||
textCache = new Map();
|
||||
}
|
||||
|
||||
test('suspending in the shell during hydration', async () => {
|
||||
const div = React.createRef(null);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div ref={div}>
|
||||
<AsyncText text="Shell" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Server render
|
||||
await resolveText('Shell');
|
||||
await serverAct(async () => {
|
||||
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
|
||||
pipe(writable);
|
||||
});
|
||||
expect(Scheduler).toHaveYielded(['Shell']);
|
||||
const dehydratedDiv = container.getElementsByTagName('div')[0];
|
||||
|
||||
// Clear the cache and start rendering on the client
|
||||
resetTextCache();
|
||||
|
||||
// Hydration suspends because the data for the shell hasn't loaded yet
|
||||
await clientAct(async () => {
|
||||
ReactDOM.hydrateRoot(container, <App />);
|
||||
});
|
||||
expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
|
||||
expect(div.current).toBe(null);
|
||||
expect(container.textContent).toBe('Shell');
|
||||
|
||||
// The shell loads and hydration finishes
|
||||
await clientAct(async () => {
|
||||
await resolveText('Shell');
|
||||
});
|
||||
expect(Scheduler).toHaveYielded(['Shell']);
|
||||
expect(div.current).toBe(dehydratedDiv);
|
||||
expect(container.textContent).toBe('Shell');
|
||||
});
|
||||
|
||||
test('suspending in the shell during a normal client render', async () => {
|
||||
// Same as previous test but during a normal client render, no hydration
|
||||
function App() {
|
||||
return <AsyncText text="Shell" />;
|
||||
}
|
||||
|
||||
const root = ReactDOM.createRoot(container);
|
||||
await clientAct(async () => {
|
||||
root.render(<App />);
|
||||
});
|
||||
expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
|
||||
|
||||
await clientAct(async () => {
|
||||
await resolveText('Shell');
|
||||
});
|
||||
expect(Scheduler).toHaveYielded(['Shell']);
|
||||
expect(container.textContent).toBe('Shell');
|
||||
});
|
||||
});
|
||||
@@ -443,6 +443,10 @@ export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes {
|
||||
return NoLanes;
|
||||
}
|
||||
|
||||
export function includesSyncLane(lanes: Lanes) {
|
||||
return (lanes & SyncLane) !== NoLanes;
|
||||
}
|
||||
|
||||
export function includesNonIdleWork(lanes: Lanes) {
|
||||
return (lanes & NonIdleLanes) !== NoLanes;
|
||||
}
|
||||
|
||||
@@ -443,6 +443,10 @@ export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes {
|
||||
return NoLanes;
|
||||
}
|
||||
|
||||
export function includesSyncLane(lanes: Lanes) {
|
||||
return (lanes & SyncLane) !== NoLanes;
|
||||
}
|
||||
|
||||
export function includesNonIdleWork(lanes: Lanes) {
|
||||
return (lanes & NonIdleLanes) !== NoLanes;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ import {
|
||||
includesSomeLane,
|
||||
mergeLanes,
|
||||
pickArbitraryLane,
|
||||
includesOnlyTransitions,
|
||||
includesSyncLane,
|
||||
} from './ReactFiberLane.new';
|
||||
import {
|
||||
getIsHydrating,
|
||||
@@ -480,25 +480,25 @@ function throwException(
|
||||
attachRetryListener(suspenseBoundary, root, wakeable, rootRenderLanes);
|
||||
return;
|
||||
} else {
|
||||
// No boundary was found. If we're inside startTransition, this is OK.
|
||||
// No boundary was found. Unless this is a sync update, this is OK.
|
||||
// We can suspend and wait for more data to arrive.
|
||||
|
||||
if (includesOnlyTransitions(rootRenderLanes)) {
|
||||
// This is a transition. Suspend. Since we're not activating a Suspense
|
||||
// boundary, this will unwind all the way to the root without performing
|
||||
// a second pass to render a fallback. (This is arguably how refresh
|
||||
// transitions should work, too, since we're not going to commit the
|
||||
// fallbacks anyway.)
|
||||
if (!includesSyncLane(rootRenderLanes)) {
|
||||
// This is not a sync update. Suspend. Since we're not activating a
|
||||
// Suspense boundary, this will unwind all the way to the root without
|
||||
// performing a second pass to render a fallback. (This is arguably how
|
||||
// refresh transitions should work, too, since we're not going to commit
|
||||
// the fallbacks anyway.)
|
||||
//
|
||||
// This case also applies to initial hydration.
|
||||
attachPingListener(root, wakeable, rootRenderLanes);
|
||||
renderDidSuspendDelayIfPossible();
|
||||
return;
|
||||
}
|
||||
|
||||
// We're not in a transition. We treat this case like an error because
|
||||
// discrete renders are expected to finish synchronously to maintain
|
||||
// consistency with external state.
|
||||
// TODO: This will error during non-transition concurrent renders, too.
|
||||
// But maybe it shouldn't?
|
||||
// This is a sync/discrete update. We treat this case like an error
|
||||
// because discrete renders are expected to produce a complete tree
|
||||
// synchronously to maintain consistency with external state.
|
||||
|
||||
// TODO: We should never call getComponentNameFromFiber in production.
|
||||
// Log a warning or something to prevent us from accidentally bundling it.
|
||||
|
||||
@@ -79,7 +79,7 @@ import {
|
||||
includesSomeLane,
|
||||
mergeLanes,
|
||||
pickArbitraryLane,
|
||||
includesOnlyTransitions,
|
||||
includesSyncLane,
|
||||
} from './ReactFiberLane.old';
|
||||
import {
|
||||
getIsHydrating,
|
||||
@@ -480,25 +480,25 @@ function throwException(
|
||||
attachRetryListener(suspenseBoundary, root, wakeable, rootRenderLanes);
|
||||
return;
|
||||
} else {
|
||||
// No boundary was found. If we're inside startTransition, this is OK.
|
||||
// No boundary was found. Unless this is a sync update, this is OK.
|
||||
// We can suspend and wait for more data to arrive.
|
||||
|
||||
if (includesOnlyTransitions(rootRenderLanes)) {
|
||||
// This is a transition. Suspend. Since we're not activating a Suspense
|
||||
// boundary, this will unwind all the way to the root without performing
|
||||
// a second pass to render a fallback. (This is arguably how refresh
|
||||
// transitions should work, too, since we're not going to commit the
|
||||
// fallbacks anyway.)
|
||||
if (!includesSyncLane(rootRenderLanes)) {
|
||||
// This is not a sync update. Suspend. Since we're not activating a
|
||||
// Suspense boundary, this will unwind all the way to the root without
|
||||
// performing a second pass to render a fallback. (This is arguably how
|
||||
// refresh transitions should work, too, since we're not going to commit
|
||||
// the fallbacks anyway.)
|
||||
//
|
||||
// This case also applies to initial hydration.
|
||||
attachPingListener(root, wakeable, rootRenderLanes);
|
||||
renderDidSuspendDelayIfPossible();
|
||||
return;
|
||||
}
|
||||
|
||||
// We're not in a transition. We treat this case like an error because
|
||||
// discrete renders are expected to finish synchronously to maintain
|
||||
// consistency with external state.
|
||||
// TODO: This will error during non-transition concurrent renders, too.
|
||||
// But maybe it shouldn't?
|
||||
// This is a sync/discrete update. We treat this case like an error
|
||||
// because discrete renders are expected to produce a complete tree
|
||||
// synchronously to maintain consistency with external state.
|
||||
|
||||
// TODO: We should never call getComponentNameFromFiber in production.
|
||||
// Log a warning or something to prevent us from accidentally bundling it.
|
||||
|
||||
@@ -389,17 +389,6 @@ describe('ReactSuspense', () => {
|
||||
expect(root).toMatchRenderedOutput('Hi');
|
||||
});
|
||||
|
||||
it('throws if tree suspends and none of the Suspense ancestors have a boundary', () => {
|
||||
ReactTestRenderer.create(<AsyncText text="Hi" ms={1000} />, {
|
||||
unstable_isConcurrent: true,
|
||||
});
|
||||
|
||||
expect(Scheduler).toFlushAndThrow(
|
||||
'AsyncText suspended while rendering, but no fallback UI was specified.',
|
||||
);
|
||||
expect(Scheduler).toHaveYielded(['Suspend! [Hi]', 'Suspend! [Hi]']);
|
||||
});
|
||||
|
||||
it('updates memoized child of suspense component when context updates (simple memo)', () => {
|
||||
const {useContext, createContext, useState, memo} = React;
|
||||
|
||||
|
||||
+9
-3
@@ -1003,9 +1003,15 @@ describe('ReactSuspenseWithNoopRenderer', () => {
|
||||
});
|
||||
|
||||
// @gate enableCache
|
||||
it('throws a helpful error when an update is suspends without a placeholder', () => {
|
||||
ReactNoop.render(<AsyncText text="Async" />);
|
||||
expect(Scheduler).toFlushAndThrow(
|
||||
it('errors when an update suspends without a placeholder during a sync update', () => {
|
||||
// This is an error because sync/discrete updates are expected to produce
|
||||
// a complete tree immediately to maintain consistency with external state
|
||||
// — we can't delay the commit.
|
||||
expect(() => {
|
||||
ReactNoop.flushSync(() => {
|
||||
ReactNoop.render(<AsyncText text="Async" />);
|
||||
});
|
||||
}).toThrow(
|
||||
'AsyncText suspended while rendering, but no fallback UI was specified.',
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user