-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathReactFiberHydrationContext.js
More file actions
1001 lines (925 loc) · 31.3 KB
/
ReactFiberHydrationContext.js
File metadata and controls
1001 lines (925 loc) · 31.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from './ReactInternalTypes';
import type {
Instance,
TextInstance,
HydratableInstance,
ActivityInstance,
SuspenseInstance,
Container,
HostContext,
} from './ReactFiberConfig';
import type {ActivityState} from './ReactFiberActivityComponent';
import type {SuspenseState} from './ReactFiberSuspenseComponent';
import type {TreeContext} from './ReactFiberTreeContext';
import type {CapturedValue} from './ReactCapturedValue';
import type {HydrationDiffNode} from './ReactFiberHydrationDiffs';
import {
HostComponent,
HostSingleton,
HostRoot,
SuspenseComponent,
ActivityComponent,
} from './ReactWorkTags';
import {createCapturedValueAtFiber} from './ReactCapturedValue';
import {createFiberFromDehydratedFragment} from './ReactFiber';
import {
shouldSetTextContent,
supportsHydration,
supportsSingletons,
getNextHydratableSibling,
getNextHydratableSiblingAfterSingleton,
getFirstHydratableChild,
getFirstHydratableChildWithinContainer,
getFirstHydratableChildWithinActivityInstance,
getFirstHydratableChildWithinSuspenseInstance,
getFirstHydratableChildWithinSingleton,
hydrateInstance,
diffHydratedPropsForDevWarnings,
describeHydratableInstanceForDevWarnings,
hydrateTextInstance,
diffHydratedTextForDevWarnings,
hydrateActivityInstance,
hydrateSuspenseInstance,
getNextHydratableInstanceAfterActivityInstance,
getNextHydratableInstanceAfterSuspenseInstance,
shouldDeleteUnhydratedTailInstances,
resolveSingletonInstance,
canHydrateInstance,
canHydrateTextInstance,
canHydrateActivityInstance,
canHydrateSuspenseInstance,
canHydrateFormStateMarker,
isFormStateMarkerMatching,
validateHydratableInstance,
validateHydratableTextInstance,
} from './ReactFiberConfig';
import {OffscreenLane} from './ReactFiberLane';
import {
getSuspendedTreeContext,
restoreSuspendedTreeContext,
} from './ReactFiberTreeContext';
import {queueRecoverableErrors} from './ReactFiberWorkLoop';
import {getRootHostContainer, getHostContext} from './ReactFiberHostContext';
import {describeDiff} from './ReactFiberHydrationDiffs';
import {runWithFiberInDEV} from './ReactCurrentFiber';
// The deepest Fiber on the stack involved in a hydration context.
// This may have been an insertion or a hydration.
let hydrationParentFiber: null | Fiber = null;
let nextHydratableInstance: null | HydratableInstance = null;
let isHydrating: 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 differences found that haven't yet been logged.
let hydrationDiffRootDEV: null | HydrationDiffNode = null;
// Hydration errors that were thrown inside this boundary
let hydrationErrors: Array<CapturedValue<mixed>> | null = null;
let rootOrSingletonContext = false;
// Stack to save hydration state when traversing into a portal. Portals render
// into a separate container that was not server-rendered, so hydration must be
// suspended for the portal's subtree and resumed afterward.
type PortalHydrationState = {
hydrationParentFiber: null | Fiber,
nextHydratableInstance: null | HydratableInstance,
isHydrating: boolean,
rootOrSingletonContext: boolean,
};
const hydrationPortalStateStack: Array<PortalHydrationState> = [];
// Builds a common ancestor tree from the root down for collecting diffs.
function buildHydrationDiffNode(
fiber: Fiber,
distanceFromLeaf: number,
): HydrationDiffNode {
if (fiber.return === null) {
// We're at the root.
if (hydrationDiffRootDEV === null) {
hydrationDiffRootDEV = {
fiber: fiber,
children: [],
serverProps: undefined,
serverTail: [],
distanceFromLeaf: distanceFromLeaf,
};
} else if (hydrationDiffRootDEV.fiber !== fiber) {
throw new Error(
'Saw multiple hydration diff roots in a pass. This is a bug in React.',
);
} else if (hydrationDiffRootDEV.distanceFromLeaf > distanceFromLeaf) {
hydrationDiffRootDEV.distanceFromLeaf = distanceFromLeaf;
}
return hydrationDiffRootDEV;
}
const siblings = buildHydrationDiffNode(
fiber.return,
distanceFromLeaf + 1,
).children;
// The same node may already exist in the parent. Since we currently always render depth first
// and rerender if we suspend or terminate early, if a shared ancestor was added we should still
// be inside of that shared ancestor which means it was the last one to be added. If this changes
// we may have to scan the whole set.
if (siblings.length > 0 && siblings[siblings.length - 1].fiber === fiber) {
const existing = siblings[siblings.length - 1];
if (existing.distanceFromLeaf > distanceFromLeaf) {
existing.distanceFromLeaf = distanceFromLeaf;
}
return existing;
}
const newNode: HydrationDiffNode = {
fiber: fiber,
children: [],
serverProps: undefined,
serverTail: [],
distanceFromLeaf: distanceFromLeaf,
};
siblings.push(newNode);
return newNode;
}
function warnIfHydrating() {
if (__DEV__) {
if (isHydrating) {
console.error(
'We should not be hydrating here. This is a bug in React. Please file a bug.',
);
}
}
}
export function markDidThrowWhileHydratingDEV() {
if (__DEV__) {
didSuspendOrErrorDEV = true;
}
}
function enterHydrationState(fiber: Fiber): boolean {
if (!supportsHydration) {
return false;
}
const parentInstance: Container = fiber.stateNode.containerInfo;
nextHydratableInstance =
getFirstHydratableChildWithinContainer(parentInstance);
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspendOrErrorDEV = false;
hydrationDiffRootDEV = null;
rootOrSingletonContext = true;
return true;
}
function reenterHydrationStateFromDehydratedActivityInstance(
fiber: Fiber,
activityInstance: ActivityInstance,
treeContext: TreeContext | null,
): boolean {
if (!supportsHydration) {
return false;
}
nextHydratableInstance =
getFirstHydratableChildWithinActivityInstance(activityInstance);
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspendOrErrorDEV = false;
hydrationDiffRootDEV = null;
rootOrSingletonContext = false;
if (treeContext !== null) {
restoreSuspendedTreeContext(fiber, treeContext);
}
return true;
}
function reenterHydrationStateFromDehydratedSuspenseInstance(
fiber: Fiber,
suspenseInstance: SuspenseInstance,
treeContext: TreeContext | null,
): boolean {
if (!supportsHydration) {
return false;
}
nextHydratableInstance =
getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspendOrErrorDEV = false;
hydrationDiffRootDEV = null;
rootOrSingletonContext = false;
if (treeContext !== null) {
restoreSuspendedTreeContext(fiber, treeContext);
}
return true;
}
function warnNonHydratedInstance(
fiber: Fiber,
rejectedCandidate: null | HydratableInstance,
) {
if (__DEV__) {
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.
return;
}
// Add this fiber to the diff tree.
const diffNode = buildHydrationDiffNode(fiber, 0);
// We use null as a signal that there was no node to match.
diffNode.serverProps = null;
if (rejectedCandidate !== null) {
const description =
describeHydratableInstanceForDevWarnings(rejectedCandidate);
diffNode.serverTail.push(description);
}
}
}
function tryHydrateInstance(
fiber: Fiber,
nextInstance: any,
hostContext: HostContext,
) {
// fiber is a HostComponent Fiber
const instance = canHydrateInstance(
nextInstance,
fiber.type,
fiber.pendingProps,
rootOrSingletonContext,
);
if (instance !== null) {
fiber.stateNode = (instance: Instance);
if (__DEV__) {
if (!didSuspendOrErrorDEV) {
const differences = diffHydratedPropsForDevWarnings(
instance,
fiber.type,
fiber.pendingProps,
hostContext,
);
if (differences !== null) {
const diffNode = buildHydrationDiffNode(fiber, 0);
diffNode.serverProps = differences;
}
}
}
hydrationParentFiber = fiber;
nextHydratableInstance = getFirstHydratableChild(instance);
rootOrSingletonContext = false;
return true;
}
return false;
}
function tryHydrateText(fiber: Fiber, nextInstance: any) {
// fiber is a HostText Fiber
const text = fiber.pendingProps;
const textInstance = canHydrateTextInstance(
nextInstance,
text,
rootOrSingletonContext,
);
if (textInstance !== null) {
fiber.stateNode = (textInstance: TextInstance);
hydrationParentFiber = fiber;
// Text Instances don't have children so there's nothing to hydrate.
nextHydratableInstance = null;
return true;
}
return false;
}
function tryHydrateActivity(
fiber: Fiber,
nextInstance: any,
): null | ActivityInstance {
// fiber is a ActivityComponent Fiber
const activityInstance = canHydrateActivityInstance(
nextInstance,
rootOrSingletonContext,
);
if (activityInstance !== null) {
const activityState: ActivityState = {
dehydrated: activityInstance,
treeContext: getSuspendedTreeContext(),
retryLane: OffscreenLane,
hydrationErrors: null,
};
fiber.memoizedState = activityState;
// Store the dehydrated fragment as a child fiber.
// This simplifies the code for getHostSibling and deleting nodes,
// since it doesn't have to consider all Suspense boundaries and
// check if they're dehydrated ones or not.
const dehydratedFragment =
createFiberFromDehydratedFragment(activityInstance);
dehydratedFragment.return = fiber;
fiber.child = dehydratedFragment;
hydrationParentFiber = fiber;
// While an Activity Instance does have children, we won't step into
// it during the first pass. Instead, we'll reenter it later.
nextHydratableInstance = null;
}
return activityInstance;
}
function tryHydrateSuspense(
fiber: Fiber,
nextInstance: any,
): null | SuspenseInstance {
// fiber is a SuspenseComponent Fiber
const suspenseInstance = canHydrateSuspenseInstance(
nextInstance,
rootOrSingletonContext,
);
if (suspenseInstance !== null) {
const suspenseState: SuspenseState = {
dehydrated: suspenseInstance,
treeContext: getSuspendedTreeContext(),
retryLane: OffscreenLane,
hydrationErrors: null,
};
fiber.memoizedState = suspenseState;
// Store the dehydrated fragment as a child fiber.
// This simplifies the code for getHostSibling and deleting nodes,
// since it doesn't have to consider all Suspense boundaries and
// check if they're dehydrated ones or not.
const dehydratedFragment =
createFiberFromDehydratedFragment(suspenseInstance);
dehydratedFragment.return = fiber;
fiber.child = dehydratedFragment;
hydrationParentFiber = fiber;
// While a Suspense Instance does have children, we won't step into
// it during the first pass. Instead, we'll reenter it later.
nextHydratableInstance = null;
}
return suspenseInstance;
}
export const HydrationMismatchException: mixed = new Error(
'Hydration Mismatch Exception: This is not a real error, and should not leak into ' +
"userspace. If you're seeing this, it's likely a bug in React.",
);
function throwOnHydrationMismatch(fiber: Fiber, fromText: boolean = false) {
let diff = '';
if (__DEV__) {
// Consume the diff root for this mismatch.
// Any other errors will get their own diffs.
const diffRoot = hydrationDiffRootDEV;
if (diffRoot !== null) {
hydrationDiffRootDEV = null;
diff = describeDiff(diffRoot);
}
}
const error = new Error(
`Hydration failed because the server rendered ${fromText ? 'text' : 'HTML'} didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:
` +
'\n' +
"- A server/client branch `if (typeof window !== 'undefined')`.\n" +
"- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n" +
"- Date formatting in a user's locale which doesn't match the server.\n" +
'- External changing data without sending a snapshot of it along with the HTML.\n' +
'- Invalid HTML tag nesting.\n' +
'\n' +
'It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n' +
'\n' +
'https://react.dev/link/hydration-mismatch' +
diff,
);
queueHydrationError(createCapturedValueAtFiber(error, fiber));
throw HydrationMismatchException;
}
function claimHydratableSingleton(fiber: Fiber): void {
if (supportsSingletons) {
if (!isHydrating) {
return;
}
const currentRootContainer = getRootHostContainer();
const currentHostContext = getHostContext();
const instance = (fiber.stateNode = resolveSingletonInstance(
fiber.type,
fiber.pendingProps,
currentRootContainer,
currentHostContext,
false,
));
if (__DEV__) {
if (!didSuspendOrErrorDEV) {
const differences = diffHydratedPropsForDevWarnings(
instance,
fiber.type,
fiber.pendingProps,
currentHostContext,
);
if (differences !== null) {
const diffNode = buildHydrationDiffNode(fiber, 0);
diffNode.serverProps = differences;
}
}
}
hydrationParentFiber = fiber;
rootOrSingletonContext = true;
nextHydratableInstance = getFirstHydratableChildWithinSingleton(
fiber.type,
instance,
nextHydratableInstance,
);
}
}
function tryToClaimNextHydratableInstance(fiber: Fiber): void {
if (!isHydrating) {
return;
}
// Validate that this is ok to render here before any mismatches.
const currentHostContext = getHostContext();
const shouldKeepWarning = validateHydratableInstance(
fiber.type,
fiber.pendingProps,
currentHostContext,
);
const nextInstance = nextHydratableInstance;
if (
!nextInstance ||
!tryHydrateInstance(fiber, nextInstance, currentHostContext)
) {
if (shouldKeepWarning) {
warnNonHydratedInstance(fiber, nextInstance);
}
throwOnHydrationMismatch(fiber);
}
}
function tryToClaimNextHydratableTextInstance(fiber: Fiber): void {
if (!isHydrating) {
return;
}
const text = fiber.pendingProps;
let shouldKeepWarning = true;
// Validate that this is ok to render here before any mismatches.
const currentHostContext = getHostContext();
shouldKeepWarning = validateHydratableTextInstance(text, currentHostContext);
const nextInstance = nextHydratableInstance;
if (!nextInstance || !tryHydrateText(fiber, nextInstance)) {
if (shouldKeepWarning) {
warnNonHydratedInstance(fiber, nextInstance);
}
throwOnHydrationMismatch(fiber);
}
}
function claimNextHydratableActivityInstance(fiber: Fiber): ActivityInstance {
const nextInstance = nextHydratableInstance;
const activityInstance = nextInstance
? tryHydrateActivity(fiber, nextInstance)
: null;
if (activityInstance === null) {
warnNonHydratedInstance(fiber, nextInstance);
throw throwOnHydrationMismatch(fiber);
}
return activityInstance;
}
function claimNextHydratableSuspenseInstance(fiber: Fiber): SuspenseInstance {
const nextInstance = nextHydratableInstance;
const suspenseInstance = nextInstance
? tryHydrateSuspense(fiber, nextInstance)
: null;
if (suspenseInstance === null) {
warnNonHydratedInstance(fiber, nextInstance);
throw throwOnHydrationMismatch(fiber);
}
return suspenseInstance;
}
export function tryToClaimNextHydratableFormMarkerInstance(
fiber: Fiber,
): boolean {
if (!isHydrating) {
return false;
}
if (nextHydratableInstance) {
const markerInstance = canHydrateFormStateMarker(
nextHydratableInstance,
rootOrSingletonContext,
);
if (markerInstance) {
// Found the marker instance.
nextHydratableInstance = getNextHydratableSibling(markerInstance);
// Return true if this marker instance should use the state passed
// to hydrateRoot.
// TODO: As an optimization, Fizz should only emit these markers if form
// state is passed at the root.
return isFormStateMarkerMatching(markerInstance);
}
}
// Should have found a marker instance. Throw an error to trigger client
// rendering. We don't bother to check if we're in a concurrent root because
// useActionState is a new API, so backwards compat is not an issue.
throwOnHydrationMismatch(fiber);
return false;
}
function prepareToHydrateHostInstance(
fiber: Fiber,
hostContext: HostContext,
): void {
if (!supportsHydration) {
throw new Error(
'Expected prepareToHydrateHostInstance() to never be called. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
const instance: Instance = fiber.stateNode;
const didHydrate = hydrateInstance(
instance,
fiber.type,
fiber.memoizedProps,
hostContext,
fiber,
);
if (!didHydrate) {
throwOnHydrationMismatch(fiber, true);
}
}
function prepareToHydrateHostTextInstance(fiber: Fiber): void {
if (!supportsHydration) {
throw new Error(
'Expected prepareToHydrateHostTextInstance() to never be called. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
const textInstance: TextInstance = fiber.stateNode;
const textContent: string = fiber.memoizedProps;
const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
let parentProps = null;
// We assume that prepareToHydrateHostTextInstance is called in a context where the
// hydration parent is the parent host component of this host text.
const returnFiber = hydrationParentFiber;
if (returnFiber !== null) {
switch (returnFiber.tag) {
case HostRoot: {
if (__DEV__) {
if (shouldWarnIfMismatchDev) {
const difference = diffHydratedTextForDevWarnings(
textInstance,
textContent,
parentProps,
);
if (difference !== null) {
const diffNode = buildHydrationDiffNode(fiber, 0);
diffNode.serverProps = difference;
}
}
}
break;
}
case HostSingleton:
case HostComponent: {
parentProps = returnFiber.memoizedProps;
if (__DEV__) {
if (shouldWarnIfMismatchDev) {
const difference = diffHydratedTextForDevWarnings(
textInstance,
textContent,
parentProps,
);
if (difference !== null) {
const diffNode = buildHydrationDiffNode(fiber, 0);
diffNode.serverProps = difference;
}
}
}
break;
}
}
// TODO: What if it's a SuspenseInstance?
}
const didHydrate = hydrateTextInstance(
textInstance,
textContent,
fiber,
parentProps,
);
if (!didHydrate) {
throwOnHydrationMismatch(fiber, true);
}
}
function prepareToHydrateHostActivityInstance(fiber: Fiber): void {
if (!supportsHydration) {
throw new Error(
'Expected prepareToHydrateHostActivityInstance() to never be called. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
const activityState: null | ActivityState = fiber.memoizedState;
const activityInstance: null | ActivityInstance =
activityState !== null ? activityState.dehydrated : null;
if (!activityInstance) {
throw new Error(
'Expected to have a hydrated activity instance. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
hydrateActivityInstance(activityInstance, fiber);
}
function prepareToHydrateHostSuspenseInstance(fiber: Fiber): void {
if (!supportsHydration) {
throw new Error(
'Expected prepareToHydrateHostSuspenseInstance() to never be called. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
const suspenseState: null | SuspenseState = fiber.memoizedState;
const suspenseInstance: null | SuspenseInstance =
suspenseState !== null ? suspenseState.dehydrated : null;
if (!suspenseInstance) {
throw new Error(
'Expected to have a hydrated suspense instance. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
hydrateSuspenseInstance(suspenseInstance, fiber);
}
function skipPastDehydratedActivityInstance(
fiber: Fiber,
): null | HydratableInstance {
const activityState: null | ActivityState = fiber.memoizedState;
const activityInstance: null | ActivityInstance =
activityState !== null ? activityState.dehydrated : null;
if (!activityInstance) {
throw new Error(
'Expected to have a hydrated suspense instance. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
return getNextHydratableInstanceAfterActivityInstance(activityInstance);
}
function skipPastDehydratedSuspenseInstance(
fiber: Fiber,
): null | HydratableInstance {
if (!supportsHydration) {
throw new Error(
'Expected skipPastDehydratedSuspenseInstance() to never be called. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
const suspenseState: null | SuspenseState = fiber.memoizedState;
const suspenseInstance: null | SuspenseInstance =
suspenseState !== null ? suspenseState.dehydrated : null;
if (!suspenseInstance) {
throw new Error(
'Expected to have a hydrated suspense instance. ' +
'This error is likely caused by a bug in React. Please file an issue.',
);
}
return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
}
function popToNextHostParent(fiber: Fiber): void {
hydrationParentFiber = fiber.return;
while (hydrationParentFiber) {
switch (hydrationParentFiber.tag) {
case HostComponent:
case ActivityComponent:
case SuspenseComponent:
rootOrSingletonContext = false;
return;
case HostSingleton:
case HostRoot:
rootOrSingletonContext = true;
return;
default:
hydrationParentFiber = hydrationParentFiber.return;
}
}
}
function popHydrationState(fiber: Fiber): boolean {
if (!supportsHydration) {
return false;
}
if (fiber !== hydrationParentFiber) {
// We're deeper than the current hydration context, inside an inserted
// tree.
return false;
}
if (!isHydrating) {
// If we're not currently hydrating but we're in a hydration context, then
// we were an insertion and now need to pop up reenter hydration of our
// siblings.
popToNextHostParent(fiber);
isHydrating = true;
return false;
}
const tag = fiber.tag;
if (supportsSingletons) {
// With float we never clear the Root, or Singleton instances. We also do not clear Instances
// that have singleton text content
if (
tag !== HostRoot &&
tag !== HostSingleton &&
!(
tag === HostComponent &&
(!shouldDeleteUnhydratedTailInstances(fiber.type) ||
shouldSetTextContent(fiber.type, fiber.memoizedProps))
)
) {
const nextInstance = nextHydratableInstance;
if (nextInstance) {
warnIfUnhydratedTailNodes(fiber);
throwOnHydrationMismatch(fiber);
}
}
} else {
// If we have any remaining hydratable nodes, we need to delete them now.
// We only do this deeper than head and body since they tend to have random
// other nodes in them. We also ignore components with pure text content in
// side of them. We also don't delete anything inside the root container.
if (
tag !== HostRoot &&
(tag !== HostComponent ||
(shouldDeleteUnhydratedTailInstances(fiber.type) &&
!shouldSetTextContent(fiber.type, fiber.memoizedProps)))
) {
const nextInstance = nextHydratableInstance;
if (nextInstance) {
warnIfUnhydratedTailNodes(fiber);
throwOnHydrationMismatch(fiber);
}
}
}
popToNextHostParent(fiber);
if (tag === SuspenseComponent) {
nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
} else if (tag === ActivityComponent) {
nextHydratableInstance = skipPastDehydratedActivityInstance(fiber);
} else if (supportsSingletons && tag === HostSingleton) {
nextHydratableInstance = getNextHydratableSiblingAfterSingleton(
fiber.type,
nextHydratableInstance,
);
} else {
nextHydratableInstance = hydrationParentFiber
? getNextHydratableSibling(fiber.stateNode)
: null;
}
return true;
}
function warnIfUnhydratedTailNodes(fiber: Fiber) {
if (__DEV__) {
let nextInstance = nextHydratableInstance;
while (nextInstance) {
const diffNode = buildHydrationDiffNode(fiber, 0);
const description =
describeHydratableInstanceForDevWarnings(nextInstance);
diffNode.serverTail.push(description);
if (description.type === 'Suspense') {
const suspenseInstance: SuspenseInstance = (nextInstance: any);
nextInstance =
getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
} else {
nextInstance = getNextHydratableSibling(nextInstance);
}
}
}
}
export function prepareToHydrateHostPortal(fiber: Fiber): void {
if (!supportsHydration) {
return;
}
// Save the current hydration state so we can restore it after the portal.
hydrationPortalStateStack.push({
hydrationParentFiber,
nextHydratableInstance,
isHydrating,
rootOrSingletonContext,
});
// Portals render into a separate container that is never server-rendered.
// Disable hydration for the portal's children so they are inserted fresh.
hydrationParentFiber = null;
nextHydratableInstance = null;
isHydrating = false;
rootOrSingletonContext = false;
}
export function popHydrationStateAfterPortal(fiber: Fiber): void {
if (!supportsHydration) {
return;
}
const savedState = hydrationPortalStateStack.pop();
if (savedState !== undefined) {
hydrationParentFiber = savedState.hydrationParentFiber;
nextHydratableInstance = savedState.nextHydratableInstance;
isHydrating = savedState.isHydrating;
rootOrSingletonContext = savedState.rootOrSingletonContext;
}
}
function resetHydrationState(): void {
if (!supportsHydration) {
return;
}
hydrationParentFiber = null;
nextHydratableInstance = null;
isHydrating = false;
didSuspendOrErrorDEV = false;
hydrationPortalStateStack.length = 0;
}
// Restore the hydration cursor when unwinding a HostComponent that already
// claimed a DOM node. This is a fork of popHydrationState that does all the
// same validity checks but restores the cursor to this fiber's DOM node
// instead of advancing past it. It also does NOT clear unhydrated tail nodes
// or throw on mismatches since we're unwinding, not completing.
//
// This is needed when replaySuspendedUnitOfWork calls unwindInterruptedWork
// before re-running beginWork on the same fiber, or when throwAndUnwindWorkLoop
// calls unwindWork on ancestor fibers.
function popHydrationStateOnInterruptedWork(fiber: Fiber): void {
if (!supportsHydration) {
return;
}
if (fiber !== hydrationParentFiber) {
// We're deeper than the current hydration context, inside an inserted
// tree. Don't touch the cursor.
return;
}
if (!isHydrating) {
// If we're not currently hydrating but we're in a hydration context, then
// we were an insertion and now need to pop up to reenter hydration of our
// siblings. Same as popHydrationState.
popToNextHostParent(fiber);
isHydrating = true;
return;
}
// We're in a valid hydration context. Restore the cursor to this fiber's
// DOM node so that when beginWork re-runs, it can claim the same node.
// Unlike popHydrationState, we do NOT check for unhydrated tail nodes
// or advance the cursor - we're restoring, not completing.
popToNextHostParent(fiber);
if (fiber.tag === HostComponent && fiber.stateNode != null) {
nextHydratableInstance = fiber.stateNode;
}
}
export function upgradeHydrationErrorsToRecoverable(): Array<
CapturedValue<mixed>,
> | null {
const queuedErrors = hydrationErrors;
if (queuedErrors !== null) {
// Successfully completed a forced client render. The errors that occurred
// during the hydration attempt are now recovered. We will log them in
// commit phase, once the entire tree has finished.
queueRecoverableErrors(queuedErrors);
hydrationErrors = null;
}
return queuedErrors;
}
function getIsHydrating(): boolean {
return isHydrating;
}
export function queueHydrationError(error: CapturedValue<mixed>): void {
if (hydrationErrors === null) {
hydrationErrors = [error];
} else {
hydrationErrors.push(error);
}
}
export function emitPendingHydrationWarnings() {
if (__DEV__) {
// If we haven't yet thrown any hydration errors by the time we reach the end we've successfully
// hydrated, however, we might still have DEV-only mismatches that we log now.
const diffRoot = hydrationDiffRootDEV;
if (diffRoot !== null) {
hydrationDiffRootDEV = null;
const diff = describeDiff(diffRoot);
// Just pick the DFS-first leaf as the owner.
// Should be good enough since most warnings only have a single error.
let diffOwner: HydrationDiffNode = diffRoot;
while (diffOwner.children.length > 0) {
diffOwner = diffOwner.children[0];
}
runWithFiberInDEV(diffOwner.fiber, () => {
console.error(
"A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. " +
'This can happen if a SSR-ed Client Component used:\n' +
'\n' +
"- A server/client branch `if (typeof window !== 'undefined')`.\n" +
"- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n" +
"- Date formatting in a user's locale which doesn't match the server.\n" +
'- External changing data without sending a snapshot of it along with the HTML.\n' +
'- Invalid HTML tag nesting.\n' +
'\n' +
'It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n' +
'\n' +
'%s%s',
'https://react.dev/link/hydration-mismatch',
diff,
);
});
}
}
}
export {
warnIfHydrating,
enterHydrationState,
getIsHydrating,
reenterHydrationStateFromDehydratedActivityInstance,
reenterHydrationStateFromDehydratedSuspenseInstance,
resetHydrationState,
popHydrationStateOnInterruptedWork,
claimHydratableSingleton,
tryToClaimNextHydratableInstance,
tryToClaimNextHydratableTextInstance,
claimNextHydratableActivityInstance,
claimNextHydratableSuspenseInstance,
prepareToHydrateHostInstance,
prepareToHydrateHostTextInstance,
prepareToHydrateHostActivityInstance,
prepareToHydrateHostSuspenseInstance,
popHydrationState,