Skip to content

Commit

Permalink
Suppress hydration warnings when a preceding sibling suspends (#24404)
Browse files Browse the repository at this point in the history
* Add failing test case for #24384

If a components suspends during hydration we expect there to be mismatches with server rendered HTML but we were not always supressing warning messages related to these expected mismatches

* Mark hydration as suspending on every thrownException

previously hydration would only be marked as supsending when a genuine error was thrown. This created an opportunity for a hydration mismatch that would warn after which later hydration mismatches would not lead to warnings. By moving the marker check earlier in the thrownException function we get the hydration context to enter the didSuspend state on both error and thrown promise cases which eliminates this gap.

* Fix failing test related to client render fallbacks

This test was actually subject to the project identified in the issue fixed in this branch. After fixing the underlying issue the assertion logic needed to change to pick the right warning which now emits after hydration successfully completes on promise resolution. I changed the container type to 'section' to make the error message slightly easier to read/understand (for me)

* Only mark didSuspend on suspense path

For unknown reasons the didSuspend was being set only on the error path and nto the suspense path. The original change hoisted this to happen on both paths. This change moves the didSuspend call to the suspense path only. This appears to be a noop because if the error path marked didSuspend it would suppress later warnings but if it does not the warning functions themsevles do that suppression (after the first one which necessarily already happened)

* gate test on hydration fallback flags

* refactor didSuspend to didSuspendOrError

the orignial behavior applied the hydration warning bailout to error paths only. originally I moved it to Suspense paths only but this commit restores it to both paths and renames the marker function as didThrow rather than didSuspend

The logic here is that for either case if we get a mismatch in hydration we want to warm up components but effectively consider the hydration for this boundary halted

* factor tests to assert different behavior between prod and dev

* add DEV suffix to didSuspendOrError to better indicate this feature should only affect dev behavior

* move tests back to ReactDOMFizzServer-test

* fix comment casing

* drop extra flag gates in tests

* add test for user error case

* remove unnecessary gate

* Make test better

it now has an intentional client mismatch that would error if there wasn't suppression brought about by the earlier error. when it client renders it has the updated value not found in the server response but we do not see a hydration warning because it was superseded by the thrown error in that render
  • Loading branch information
gnoff authored Apr 20, 2022
1 parent 0dc4e66 commit 9ae80d6
Show file tree
Hide file tree
Showing 6 changed files with 290 additions and 29 deletions.
243 changes: 243 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMFizzServer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2841,4 +2841,247 @@ describe('ReactDOMFizzServer', () => {
expect(window.__test_outlet).toBe(1);
});
});

// @gate experimental && enableClientRenderFallbackOnTextMismatch
it('#24384: Suspending should halt hydration warnings while still allowing siblings to warm up', async () => {
const makeApp = () => {
let resolve, resolved;
const promise = new Promise(r => {
resolve = () => {
resolved = true;
return r();
};
});
function ComponentThatSuspends() {
if (!resolved) {
throw promise;
}
return <p>A</p>;
}

const App = ({text}) => {
return (
<div>
<Suspense fallback={<h1>Loading...</h1>}>
<ComponentThatSuspends />
<h2 name={text}>{text}</h2>
</Suspense>
</div>
);
};

return [App, resolve];
};

const [ServerApp, serverResolve] = makeApp();
await act(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(
<ServerApp text="initial" />,
);
pipe(writable);
});
await act(() => {
serverResolve();
});

expect(getVisibleChildren(container)).toEqual(
<div>
<p>A</p>
<h2 name="initial">initial</h2>
</div>,
);

// The client app is rendered with an intentionally incorrect text. The still Suspended component causes
// hydration to fail silently (allowing for cache warming but otherwise skipping this boundary) until it
// resolves.
const [ClientApp, clientResolve] = makeApp();
ReactDOMClient.hydrateRoot(container, <ClientApp text="replaced" />, {
onRecoverableError(error) {
Scheduler.unstable_yieldValue(
'Logged recoverable error: ' + error.message,
);
},
});
Scheduler.unstable_flushAll();

expect(getVisibleChildren(container)).toEqual(
<div>
<p>A</p>
<h2 name="initial">initial</h2>
</div>,
);

// Now that the boundary resolves to it's children the hydration completes and discovers that there is a mismatch requiring
// client-side rendering.
await clientResolve();
expect(() => {
expect(Scheduler).toFlushAndYield([
'Logged recoverable error: Text content does not match server-rendered HTML.',
'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.',
]);
}).toErrorDev(
'Warning: Prop `name` did not match. Server: "initial" Client: "replaced"',
);
expect(getVisibleChildren(container)).toEqual(
<div>
<p>A</p>
<h2 name="replaced">replaced</h2>
</div>,
);

expect(Scheduler).toFlushAndYield([]);
});

// @gate experimental && enableClientRenderFallbackOnTextMismatch
it('only warns once on hydration mismatch while within a suspense boundary', async () => {
const originalConsoleError = console.error;
const mockError = jest.fn();
console.error = (...args) => {
mockError(...args.map(normalizeCodeLocInfo));
};

const App = ({text}) => {
return (
<div>
<Suspense fallback={<h1>Loading...</h1>}>
<h2>{text}</h2>
<h2>{text}</h2>
<h2>{text}</h2>
</Suspense>
</div>
);
};

try {
await act(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(
<App text="initial" />,
);
pipe(writable);
});

expect(getVisibleChildren(container)).toEqual(
<div>
<h2>initial</h2>
<h2>initial</h2>
<h2>initial</h2>
</div>,
);

ReactDOMClient.hydrateRoot(container, <App text="replaced" />, {
onRecoverableError(error) {
Scheduler.unstable_yieldValue(
'Logged recoverable error: ' + error.message,
);
},
});
expect(Scheduler).toFlushAndYield([
'Logged recoverable error: Text content does not match server-rendered HTML.',
'Logged recoverable error: Text content does not match server-rendered HTML.',
'Logged recoverable error: Text content does not match server-rendered HTML.',
'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.',
]);

expect(getVisibleChildren(container)).toEqual(
<div>
<h2>replaced</h2>
<h2>replaced</h2>
<h2>replaced</h2>
</div>,
);

expect(Scheduler).toFlushAndYield([]);
if (__DEV__) {
expect(mockError.mock.calls.length).toBe(1);
expect(mockError.mock.calls[0]).toEqual([
'Warning: Text content did not match. Server: "%s" Client: "%s"%s',
'initial',
'replaced',
'\n' +
' in h2 (at **)\n' +
' in Suspense (at **)\n' +
' in div (at **)\n' +
' in App (at **)',
]);
} else {
expect(mockError.mock.calls.length).toBe(0);
}
} finally {
console.error = originalConsoleError;
}
});

// @gate experimental
it('supresses hydration warnings when an error occurs within a Suspense boundary', async () => {
let isClient = false;
let shouldThrow = true;

function ThrowUntilOnClient({children}) {
if (isClient && shouldThrow) {
throw new Error('uh oh');
}
return children;
}

function StopThrowingOnClient() {
if (isClient) {
shouldThrow = false;
}
return null;
}

const App = () => {
return (
<div>
<Suspense fallback={<h1>Loading...</h1>}>
<ThrowUntilOnClient>
<h1>one</h1>
</ThrowUntilOnClient>
<h2>two</h2>
<h3>{isClient ? 'five' : 'three'}</h3>
<StopThrowingOnClient />
</Suspense>
</div>
);
};

await act(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});

expect(getVisibleChildren(container)).toEqual(
<div>
<h1>one</h1>
<h2>two</h2>
<h3>three</h3>
</div>,
);

isClient = true;

ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.unstable_yieldValue(
'Logged recoverable error: ' + error.message,
);
},
});
expect(Scheduler).toFlushAndYield([
'Logged recoverable error: uh oh',
'Logged recoverable error: Hydration failed because the initial UI does not match what was rendered on the server.',
'Logged recoverable error: Hydration failed because the initial UI does not match what was rendered on the server.',
'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.',
]);

expect(getVisibleChildren(container)).toEqual(
<div>
<h1>one</h1>
<h2>two</h2>
<h3>five</h3>
</div>,
);

expect(Scheduler).toFlushAndYield([]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ describe('ReactDOMServerPartialHydration', () => {
}
try {
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
const container = document.createElement('section');
container.innerHTML = finalHTML;
expect(Scheduler).toHaveYielded([
'Hello',
Expand Down Expand Up @@ -350,12 +350,14 @@ describe('ReactDOMServerPartialHydration', () => {
);

if (__DEV__) {
expect(mockError.mock.calls[0]).toEqual([
const secondToLastCall =
mockError.mock.calls[mockError.mock.calls.length - 2];
expect(secondToLastCall).toEqual([
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'div',
'div',
'article',
'section',
'\n' +
' in div (at **)\n' +
' in article (at **)\n' +
' in Component (at **)\n' +
' in Suspense (at **)\n' +
' in App (at **)',
Expand Down
21 changes: 12 additions & 9 deletions packages/react-reconciler/src/ReactFiberHydrationContext.new.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ import {queueRecoverableErrors} from './ReactFiberWorkLoop.new';
let hydrationParentFiber: null | Fiber = null;
let nextHydratableInstance: null | HydratableInstance = null;
let isHydrating: boolean = false;
let didSuspend: boolean = false;

// This flag allows for warning supression when we expect there to be mismatches
// due to earlier mismatches or a suspended fiber.
let didSuspendOrErrorDEV: boolean = false;

// Hydration errors that were thrown inside this boundary
let hydrationErrors: Array<mixed> | null = null;
Expand All @@ -95,9 +98,9 @@ function warnIfHydrating() {
}
}

export function markDidSuspendWhileHydratingDEV() {
export function markDidThrowWhileHydratingDEV() {
if (__DEV__) {
didSuspend = true;
didSuspendOrErrorDEV = true;
}
}

Expand All @@ -113,7 +116,7 @@ function enterHydrationState(fiber: Fiber): boolean {
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspend = false;
didSuspendOrErrorDEV = false;
return true;
}

Expand All @@ -131,7 +134,7 @@ function reenterHydrationStateFromDehydratedSuspenseInstance(
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspend = false;
didSuspendOrErrorDEV = false;
if (treeContext !== null) {
restoreSuspendedTreeContext(fiber, treeContext);
}
Expand Down Expand Up @@ -196,7 +199,7 @@ function deleteHydratableInstance(

function warnNonhydratedInstance(returnFiber: Fiber, fiber: Fiber) {
if (__DEV__) {
if (didSuspend) {
if (didSuspendOrErrorDEV) {
// Inside a boundary that already suspended. We're currently rendering the
// siblings of a suspended node. The mismatch may be due to the missing
// data, so it's probably a false positive.
Expand Down Expand Up @@ -444,7 +447,7 @@ function prepareToHydrateHostInstance(
}

const instance: Instance = fiber.stateNode;
const shouldWarnIfMismatchDev = !didSuspend;
const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
const updatePayload = hydrateInstance(
instance,
fiber.type,
Expand Down Expand Up @@ -474,7 +477,7 @@ function prepareToHydrateHostTextInstance(fiber: Fiber): boolean {

const textInstance: TextInstance = fiber.stateNode;
const textContent: string = fiber.memoizedProps;
const shouldWarnIfMismatchDev = !didSuspend;
const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
const shouldUpdate = hydrateTextInstance(
textInstance,
textContent,
Expand Down Expand Up @@ -653,7 +656,7 @@ function resetHydrationState(): void {
hydrationParentFiber = null;
nextHydratableInstance = null;
isHydrating = false;
didSuspend = false;
didSuspendOrErrorDEV = false;
}

export function upgradeHydrationErrorsToRecoverable(): void {
Expand Down
Loading

0 comments on commit 9ae80d6

Please sign in to comment.