@samitouri / QOS-React-2 / commits / 33226fadaa

Check for store mutations before commit (#22290)

* [useSyncExternalStore] Remove extra hook object Because we already track `getSnapshot` and `value` on the store instance, we don't need to also track them as effect dependencies. And because the effect doesn't require any clean-up, we don't need to track a `destroy` function. So, we don't need to store any additional state for this effect. We can call `pushEffect` directly, and only during renders where something has changed. This saves some memory, but my main motivation is because I plan to use this same logic to schedule a pre-commit consistency check. (See the inline comments for more details.) * Split shouldTimeSlice into two separate functions Lanes that are blocking (SyncLane, and DefaultLane inside a blocking- by-default root) are always blocking for a given root. Whereas expired lanes can expire while the render phase is already in progress. I want to check if a lane is blocking without checking whether it expired, so I split `shouldTimeSlice` into two separate functions. I'll use this in the next step. * Check for store mutations before commit When a store is read for the first time, or when `subscribe` or `getSnapshot` changes, during a concurrent render, we have to check at the end of the render phase whether the store was mutated by an concurrent event. In the userspace shim, we perform this check in a layout effect, and patch up any inconsistencies by scheduling another render + commit. However, even though we patch them up in the next render, the parent layout effects that fire in the original render will still observe an inconsistent tree. In the native implementation, we can instead check for inconsistencies right after the root is completed, before entering the commit phase. If we do detect a mutaiton, we can discard the tree and re-render before firing any effects. The re-render is synchronous to block further concurrent mutations (which is also what we do to recover from tearing bugs that result in an error). After the synchronous re-render, we can assume the tree the tree is consistent and continue with the normal algorithm for finishing a completed root (i.e. either suspend or commit). The result is that layout effects will always observe a consistent tree.

Andrew Clark committed Sep 13, 2021 at 11:07 UTC 33226fadaac7b23634852eee78c4f1c84c5b2bbb
10 files changed +747 -201
packages/react-debug-tools/src/ReactDebugHooks.js
-1
@@ -273,7 +273,6 @@ function useSyncExternalStore<T>(
273 // Advance the current hook index the same number of times
274 // so that subsequent hooks have the right memoized state.
275 nextHook(); // SyncExternalStore
276 - nextHook(); // LayoutEffect
276 nextHook(); // Effect
277 const value = getSnapshot();
278 hookLog.push({
packages/react-reconciler/src/ReactFiberFlags.js
+28 -26
@@ -12,51 +12,53 @@ import {enableCreateEventHandleAPI} from 'shared/ReactFeatureFlags';
12 export type Flags = number;
13
14 // Don't change these two values. They're used by React Dev Tools.
15 -export const NoFlags = /* */ 0b00000000000000000000000;
16 -export const PerformedWork = /* */ 0b00000000000000000000001;
15 +export const NoFlags = /* */ 0b000000000000000000000000;
16 +export const PerformedWork = /* */ 0b000000000000000000000001;
17
18 // You can change the rest (and add more).
19 -export const Placement = /* */ 0b00000000000000000000010;
20 -export const Update = /* */ 0b00000000000000000000100;
19 +export const Placement = /* */ 0b000000000000000000000010;
20 +export const Update = /* */ 0b000000000000000000000100;
21 export const PlacementAndUpdate = /* */ Placement | Update;
22 -export const Deletion = /* */ 0b00000000000000000001000;
23 -export const ChildDeletion = /* */ 0b00000000000000000010000;
24 -export const ContentReset = /* */ 0b00000000000000000100000;
25 -export const Callback = /* */ 0b00000000000000001000000;
26 -export const DidCapture = /* */ 0b00000000000000010000000;
27 -export const Ref = /* */ 0b00000000000000100000000;
28 -export const Snapshot = /* */ 0b00000000000001000000000;
29 -export const Passive = /* */ 0b00000000000010000000000;
30 -export const Hydrating = /* */ 0b00000000000100000000000;
22 +export const Deletion = /* */ 0b000000000000000000001000;
23 +export const ChildDeletion = /* */ 0b000000000000000000010000;
24 +export const ContentReset = /* */ 0b000000000000000000100000;
25 +export const Callback = /* */ 0b000000000000000001000000;
26 +export const DidCapture = /* */ 0b000000000000000010000000;
27 +export const Ref = /* */ 0b000000000000000100000000;
28 +export const Snapshot = /* */ 0b000000000000001000000000;
29 +export const Passive = /* */ 0b000000000000010000000000;
30 +export const Hydrating = /* */ 0b000000000000100000000000;
31 export const HydratingAndUpdate = /* */ Hydrating | Update;
32 -export const Visibility = /* */ 0b00000000001000000000000;
32 +export const Visibility = /* */ 0b000000000001000000000000;
33 +export const StoreConsistency = /* */ 0b000000000010000000000000;
34
34 -export const LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot;
35 +export const LifecycleEffectMask =
36 + Passive | Update | Callback | Ref | Snapshot | StoreConsistency;
37
38 // Union of all commit flags (flags with the lifetime of a particular commit)
37 -export const HostEffectMask = /* */ 0b00000000001111111111111;
39 +export const HostEffectMask = /* */ 0b000000000011111111111111;
40
41 // These are not really side effects, but we still reuse this field.
40 -export const Incomplete = /* */ 0b00000000010000000000000;
41 -export const ShouldCapture = /* */ 0b00000000100000000000000;
42 -export const ForceUpdateForLegacySuspense = /* */ 0b00000001000000000000000;
43 -export const DidPropagateContext = /* */ 0b00000010000000000000000;
44 -export const NeedsPropagation = /* */ 0b00000100000000000000000;
42 +export const Incomplete = /* */ 0b000000000100000000000000;
43 +export const ShouldCapture = /* */ 0b000000001000000000000000;
44 +export const ForceUpdateForLegacySuspense = /* */ 0b000000010000000000000000;
45 +export const DidPropagateContext = /* */ 0b000000100000000000000000;
46 +export const NeedsPropagation = /* */ 0b000001000000000000000000;
47
48 // Static tags describe aspects of a fiber that are not specific to a render,
49 // e.g. a fiber uses a passive effect (even if there are no updates on this particular render).
50 // This enables us to defer more work in the unmount case,
51 // since we can defer traversing the tree during layout to look for Passive effects,
52 // and instead rely on the static flag as a signal that there may be cleanup work.
51 -export const RefStatic = /* */ 0b00001000000000000000000;
52 -export const LayoutStatic = /* */ 0b00010000000000000000000;
53 -export const PassiveStatic = /* */ 0b00100000000000000000000;
53 +export const RefStatic = /* */ 0b000010000000000000000000;
54 +export const LayoutStatic = /* */ 0b000100000000000000000000;
55 +export const PassiveStatic = /* */ 0b001000000000000000000000;
56
57 // These flags allow us to traverse to fibers that have effects on mount
58 // without traversing the entire tree after every commit for
59 // double invoking
58 -export const MountLayoutDev = /* */ 0b01000000000000000000000;
59 -export const MountPassiveDev = /* */ 0b10000000000000000000000;
60 +export const MountLayoutDev = /* */ 0b010000000000000000000000;
61 +export const MountPassiveDev = /* */ 0b100000000000000000000000;
62
63 // Groups of flags that are used in the commit phase to skip over trees that
64 // don't contain effects, by checking subtreeFlags.
packages/react-reconciler/src/ReactFiberHooks.new.js
+136 -49
@@ -44,6 +44,7 @@ import {
44 SyncLane,
45 NoLanes,
46 isSubsetOfLanes,
47 + includesBlockingLane,
48 mergeLanes,
49 removeLanes,
50 intersectLanes,
@@ -68,6 +69,7 @@ import {
69 PassiveStatic as PassiveStaticEffect,
70 StaticMask as StaticMaskEffect,
71 Update as UpdateEffect,
72 + StoreConsistency,
73 } from './ReactFiberFlags';
74 import {
75 HasEffect as HookHasEffect,
@@ -166,7 +168,15 @@ type StoreInstance<T> = {|
168 getSnapshot: () => T,
169 |};
170
169 -export type FunctionComponentUpdateQueue = {|lastEffect: Effect | null|};
171 +type StoreConsistencyCheck<T> = {|
172 + value: T,
173 + getSnapshot: () => T,
174 +|};
175 +
176 +export type FunctionComponentUpdateQueue = {|
177 + lastEffect: Effect | null,
178 + stores: Array<StoreConsistencyCheck<any>> | null,
179 +|};
180
181 type BasicStateAction<S> = (S => S) | S;
182
@@ -689,6 +699,7 @@ function updateWorkInProgressHook(): Hook {
699 function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
700 return {
701 lastEffect: null,
702 + stores: null,
703 };
704 }
705
@@ -1256,6 +1267,7 @@ function mountSyncExternalStore<T>(
1267 subscribe: (() => void) => () => void,
1268 getSnapshot: () => T,
1269 ): T {
1270 + const fiber = currentlyRenderingFiber;
1271 const hook = mountWorkInProgressHook();
1272 // Read the current snapshot from the store on every render. This breaks the
1273 // normal rules of React, and only works because store updates are
@@ -1277,13 +1289,45 @@ function mountSyncExternalStore<T>(
1289 getSnapshot,
1290 };
1291 hook.queue = inst;
1280 - return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot);
1292 +
1293 + // Schedule an effect to subscribe to the store.
1294 + mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
1295 +
1296 + // Schedule an effect to update the mutable instance fields. We will update
1297 + // this whenever subscribe, getSnapshot, or value changes. Because there's no
1298 + // clean-up function, and we track the deps correctly, we can call pushEffect
1299 + // directly, without storing any additional state. For the same reason, we
1300 + // don't need to set a static flag, either.
1301 + // TODO: We can move this to the passive phase once we add a pre-commit
1302 + // consistency check. See the next comment.
1303 + fiber.flags |= PassiveEffect;
1304 + pushEffect(
1305 + HookHasEffect | HookPassive,
1306 + updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot),
1307 + undefined,
1308 + null,
1309 + );
1310 +
1311 + // Unless we're rendering a blocking lane, schedule a consistency check. Right
1312 + // before committing, we will walk the tree and check if any of the stores
1313 + // were mutated.
1314 + const root: FiberRoot | null = getWorkInProgressRoot();
1315 + invariant(
1316 + root !== null,
1317 + 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1318 + );
1319 + if (!includesBlockingLane(root, renderLanes)) {
1320 + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
1321 + }
1322 +
1323 + return nextSnapshot;
1324 }
1325
1326 function updateSyncExternalStore<T>(
1327 subscribe: (() => void) => () => void,
1328 getSnapshot: () => T,
1329 ): T {
1330 + const fiber = currentlyRenderingFiber;
1331 const hook = updateWorkInProgressHook();
1332 // Read the current snapshot from the store on every render. This breaks the
1333 // normal rules of React, and only works because store updates are
@@ -1300,66 +1344,109 @@ function updateSyncExternalStore<T>(
1344 }
1345 }
1346 const prevSnapshot = hook.memoizedState;
1303 - if (!is(prevSnapshot, nextSnapshot)) {
1347 + const snapshotChanged = !is(prevSnapshot, nextSnapshot);
1348 + if (snapshotChanged) {
1349 hook.memoizedState = nextSnapshot;
1350 markWorkInProgressReceivedUpdate();
1351 }
1352 const inst = hook.queue;
1308 - return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot);
1353 +
1354 + updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
1355 + subscribe,
1356 + ]);
1357 +
1358 + // Whenever getSnapshot or subscribe changes, we need to check in the
1359 + // commit phase if there was an interleaved mutation. In concurrent mode
1360 + // this can happen all the time, but even in synchronous mode, an earlier
1361 + // effect may have mutated the store.
1362 + if (
1363 + inst.getSnapshot !== getSnapshot ||
1364 + snapshotChanged ||
1365 + // Check if the susbcribe function changed. We can save some memory by
1366 + // checking whether we scheduled a subscription effect above.
1367 + (workInProgressHook !== null &&
1368 + workInProgressHook.memoizedState.tag & HookHasEffect)
1369 + ) {
1370 + fiber.flags |= PassiveEffect;
1371 + pushEffect(
1372 + HookHasEffect | HookPassive,
1373 + updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot),
1374 + undefined,
1375 + null,
1376 + );
1377 +
1378 + // Unless we're rendering a blocking lane, schedule a consistency check.
1379 + // Right before committing, we will walk the tree and check if any of the
1380 + // stores were mutated.
1381 + const root: FiberRoot | null = getWorkInProgressRoot();
1382 + invariant(
1383 + root !== null,
1384 + 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1385 + );
1386 + if (!includesBlockingLane(root, renderLanes)) {
1387 + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
1388 + }
1389 + }
1390 +
1391 + return nextSnapshot;
1392 }
1393
1311 -function useSyncExternalStore<T>(
1312 - hook: Hook,
1313 - inst: StoreInstance<T>,
1314 - subscribe: (() => void) => () => void,
1394 +function pushStoreConsistencyCheck<T>(
1395 + fiber: Fiber,
1396 getSnapshot: () => T,
1397 + renderedSnapshot: T,
1398 +) {
1399 + fiber.flags |= StoreConsistency;
1400 + const check: StoreConsistencyCheck<T> = {
1401 + getSnapshot,
1402 + value: renderedSnapshot,
1403 + };
1404 + let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any);
1405 + if (componentUpdateQueue === null) {
1406 + componentUpdateQueue = createFunctionComponentUpdateQueue();
1407 + currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any);
1408 + componentUpdateQueue.stores = [check];
1409 + } else {
1410 + const stores = componentUpdateQueue.stores;
1411 + if (stores === null) {
1412 + componentUpdateQueue.stores = [check];
1413 + } else {
1414 + stores.push(check);
1415 + }
1416 + }
1417 +}
1418 +
1419 +function updateStoreInstance<T>(
1420 + fiber: Fiber,
1421 + inst: StoreInstance<T>,
1422 nextSnapshot: T,
1317 -): T {
1318 - const fiber = currentlyRenderingFiber;
1319 - const dispatcher = ReactCurrentDispatcher.current;
1423 + getSnapshot: () => T,
1424 +) {
1425 + // These are updated in the passive phase
1426 + inst.value = nextSnapshot;
1427 + inst.getSnapshot = getSnapshot;
1428 +
1429 + // Something may have been mutated in between render and commit. This could
1430 + // have been in an event that fired before the passive effects, or it could
1431 + // have been in a layout effect. In that case, we would have used the old
1432 + // snapsho and getSnapshot values to bail out. We need to check one more time.
1433 + if (checkIfSnapshotChanged(inst)) {
1434 + // Force a re-render.
1435 + forceStoreRerender(fiber);
1436 + }
1437 +}
1438
1321 - // Track the latest getSnapshot function with a ref. This needs to be updated
1322 - // in the layout phase so we can access it during the tearing check that
1323 - // happens on subscribe.
1324 - // TODO: Circumvent SSR warning
1325 - dispatcher.useLayoutEffect(() => {
1326 - inst.value = nextSnapshot;
1327 - inst.getSnapshot = getSnapshot;
1328 -
1329 - // Whenever getSnapshot or subscribe changes, we need to check in the
1330 - // commit phase if there was an interleaved mutation. In concurrent mode
1331 - // this can happen all the time, but even in synchronous mode, an earlier
1332 - // effect may have mutated the store.
1333 - // TODO: Move the tearing checks to an earlier, pre-commit phase so that the
1334 - // layout effects always observe a consistent tree.
1439 +function subscribeToStore(fiber, inst, subscribe) {
1440 + const handleStoreChange = () => {
1441 + // The store changed. Check if the snapshot changed since the last time we
1442 + // read from the store.
1443 if (checkIfSnapshotChanged(inst)) {
1444 // Force a re-render.
1445 forceStoreRerender(fiber);
1446 }
1339 - }, [subscribe, nextSnapshot, getSnapshot]);
1340 -
1341 - dispatcher.useEffect(() => {
1342 - const handleStoreChange = () => {
1343 - // TODO: Because there is no cross-renderer API for batching updates, it's
1344 - // up to the consumer of this library to wrap their subscription event
1345 - // with unstable_batchedUpdates. Should we try to detect when this isn't
1346 - // the case and print a warning in development?
1347 -
1348 - // The store changed. Check if the snapshot changed since the last time we
1349 - // read from the store.
1350 - if (checkIfSnapshotChanged(inst)) {
1351 - // Force a re-render.
1352 - forceStoreRerender(fiber);
1353 - }
1354 - };
1355 - // Check for changes right before subscribing. Subsequent changes will be
1356 - // detected in the subscription handler.
1357 - handleStoreChange();
1358 - // Subscribe to the store and return a clean-up function.
1359 - return subscribe(handleStoreChange);
1360 - }, [subscribe]);
1361 -
1362 - return nextSnapshot;
1447 + };
1448 + // Subscribe to the store and return a clean-up function.
1449 + return subscribe(handleStoreChange);
1450 }
1451
1452 function checkIfSnapshotChanged(inst) {
packages/react-reconciler/src/ReactFiberHooks.old.js
+136 -49
@@ -44,6 +44,7 @@ import {
44 SyncLane,
45 NoLanes,
46 isSubsetOfLanes,
47 + includesBlockingLane,
48 mergeLanes,
49 removeLanes,
50 intersectLanes,
@@ -68,6 +69,7 @@ import {
69 PassiveStatic as PassiveStaticEffect,
70 StaticMask as StaticMaskEffect,
71 Update as UpdateEffect,
72 + StoreConsistency,
73 } from './ReactFiberFlags';
74 import {
75 HasEffect as HookHasEffect,
@@ -166,7 +168,15 @@ type StoreInstance<T> = {|
168 getSnapshot: () => T,
169 |};
170
169 -export type FunctionComponentUpdateQueue = {|lastEffect: Effect | null|};
171 +type StoreConsistencyCheck<T> = {|
172 + value: T,
173 + getSnapshot: () => T,
174 +|};
175 +
176 +export type FunctionComponentUpdateQueue = {|
177 + lastEffect: Effect | null,
178 + stores: Array<StoreConsistencyCheck<any>> | null,
179 +|};
180
181 type BasicStateAction<S> = (S => S) | S;
182
@@ -689,6 +699,7 @@ function updateWorkInProgressHook(): Hook {
699 function createFunctionComponentUpdateQueue(): FunctionComponentUpdateQueue {
700 return {
701 lastEffect: null,
702 + stores: null,
703 };
704 }
705
@@ -1256,6 +1267,7 @@ function mountSyncExternalStore<T>(
1267 subscribe: (() => void) => () => void,
1268 getSnapshot: () => T,
1269 ): T {
1270 + const fiber = currentlyRenderingFiber;
1271 const hook = mountWorkInProgressHook();
1272 // Read the current snapshot from the store on every render. This breaks the
1273 // normal rules of React, and only works because store updates are
@@ -1277,13 +1289,45 @@ function mountSyncExternalStore<T>(
1289 getSnapshot,
1290 };
1291 hook.queue = inst;
1280 - return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot);
1292 +
1293 + // Schedule an effect to subscribe to the store.
1294 + mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
1295 +
1296 + // Schedule an effect to update the mutable instance fields. We will update
1297 + // this whenever subscribe, getSnapshot, or value changes. Because there's no
1298 + // clean-up function, and we track the deps correctly, we can call pushEffect
1299 + // directly, without storing any additional state. For the same reason, we
1300 + // don't need to set a static flag, either.
1301 + // TODO: We can move this to the passive phase once we add a pre-commit
1302 + // consistency check. See the next comment.
1303 + fiber.flags |= PassiveEffect;
1304 + pushEffect(
1305 + HookHasEffect | HookPassive,
1306 + updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot),
1307 + undefined,
1308 + null,
1309 + );
1310 +
1311 + // Unless we're rendering a blocking lane, schedule a consistency check. Right
1312 + // before committing, we will walk the tree and check if any of the stores
1313 + // were mutated.
1314 + const root: FiberRoot | null = getWorkInProgressRoot();
1315 + invariant(
1316 + root !== null,
1317 + 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1318 + );
1319 + if (!includesBlockingLane(root, renderLanes)) {
1320 + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
1321 + }
1322 +
1323 + return nextSnapshot;
1324 }
1325
1326 function updateSyncExternalStore<T>(
1327 subscribe: (() => void) => () => void,
1328 getSnapshot: () => T,
1329 ): T {
1330 + const fiber = currentlyRenderingFiber;
1331 const hook = updateWorkInProgressHook();
1332 // Read the current snapshot from the store on every render. This breaks the
1333 // normal rules of React, and only works because store updates are
@@ -1300,66 +1344,109 @@ function updateSyncExternalStore<T>(
1344 }
1345 }
1346 const prevSnapshot = hook.memoizedState;
1303 - if (!is(prevSnapshot, nextSnapshot)) {
1347 + const snapshotChanged = !is(prevSnapshot, nextSnapshot);
1348 + if (snapshotChanged) {
1349 hook.memoizedState = nextSnapshot;
1350 markWorkInProgressReceivedUpdate();
1351 }
1352 const inst = hook.queue;
1308 - return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot);
1353 +
1354 + updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
1355 + subscribe,
1356 + ]);
1357 +
1358 + // Whenever getSnapshot or subscribe changes, we need to check in the
1359 + // commit phase if there was an interleaved mutation. In concurrent mode
1360 + // this can happen all the time, but even in synchronous mode, an earlier
1361 + // effect may have mutated the store.
1362 + if (
1363 + inst.getSnapshot !== getSnapshot ||
1364 + snapshotChanged ||
1365 + // Check if the susbcribe function changed. We can save some memory by
1366 + // checking whether we scheduled a subscription effect above.
1367 + (workInProgressHook !== null &&
1368 + workInProgressHook.memoizedState.tag & HookHasEffect)
1369 + ) {
1370 + fiber.flags |= PassiveEffect;
1371 + pushEffect(
1372 + HookHasEffect | HookPassive,
1373 + updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot),
1374 + undefined,
1375 + null,
1376 + );
1377 +
1378 + // Unless we're rendering a blocking lane, schedule a consistency check.
1379 + // Right before committing, we will walk the tree and check if any of the
1380 + // stores were mutated.
1381 + const root: FiberRoot | null = getWorkInProgressRoot();
1382 + invariant(
1383 + root !== null,
1384 + 'Expected a work-in-progress root. This is a bug in React. Please file an issue.',
1385 + );
1386 + if (!includesBlockingLane(root, renderLanes)) {
1387 + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
1388 + }
1389 + }
1390 +
1391 + return nextSnapshot;
1392 }
1393
1311 -function useSyncExternalStore<T>(
1312 - hook: Hook,
1313 - inst: StoreInstance<T>,
1314 - subscribe: (() => void) => () => void,
1394 +function pushStoreConsistencyCheck<T>(
1395 + fiber: Fiber,
1396 getSnapshot: () => T,
1397 + renderedSnapshot: T,
1398 +) {
1399 + fiber.flags |= StoreConsistency;
1400 + const check: StoreConsistencyCheck<T> = {
1401 + getSnapshot,
1402 + value: renderedSnapshot,
1403 + };
1404 + let componentUpdateQueue: null | FunctionComponentUpdateQueue = (currentlyRenderingFiber.updateQueue: any);
1405 + if (componentUpdateQueue === null) {
1406 + componentUpdateQueue = createFunctionComponentUpdateQueue();
1407 + currentlyRenderingFiber.updateQueue = (componentUpdateQueue: any);
1408 + componentUpdateQueue.stores = [check];
1409 + } else {
1410 + const stores = componentUpdateQueue.stores;
1411 + if (stores === null) {
1412 + componentUpdateQueue.stores = [check];
1413 + } else {
1414 + stores.push(check);
1415 + }
1416 + }
1417 +}
1418 +
1419 +function updateStoreInstance<T>(
1420 + fiber: Fiber,
1421 + inst: StoreInstance<T>,
1422 nextSnapshot: T,
1317 -): T {
1318 - const fiber = currentlyRenderingFiber;
1319 - const dispatcher = ReactCurrentDispatcher.current;
1423 + getSnapshot: () => T,
1424 +) {
1425 + // These are updated in the passive phase
1426 + inst.value = nextSnapshot;
1427 + inst.getSnapshot = getSnapshot;
1428 +
1429 + // Something may have been mutated in between render and commit. This could
1430 + // have been in an event that fired before the passive effects, or it could
1431 + // have been in a layout effect. In that case, we would have used the old
1432 + // snapsho and getSnapshot values to bail out. We need to check one more time.
1433 + if (checkIfSnapshotChanged(inst)) {
1434 + // Force a re-render.
1435 + forceStoreRerender(fiber);
1436 + }
1437 +}
1438
1321 - // Track the latest getSnapshot function with a ref. This needs to be updated
1322 - // in the layout phase so we can access it during the tearing check that
1323 - // happens on subscribe.
1324 - // TODO: Circumvent SSR warning
1325 - dispatcher.useLayoutEffect(() => {
1326 - inst.value = nextSnapshot;
1327 - inst.getSnapshot = getSnapshot;
1328 -
1329 - // Whenever getSnapshot or subscribe changes, we need to check in the
1330 - // commit phase if there was an interleaved mutation. In concurrent mode
1331 - // this can happen all the time, but even in synchronous mode, an earlier
1332 - // effect may have mutated the store.
1333 - // TODO: Move the tearing checks to an earlier, pre-commit phase so that the
1334 - // layout effects always observe a consistent tree.
1439 +function subscribeToStore(fiber, inst, subscribe) {
1440 + const handleStoreChange = () => {
1441 + // The store changed. Check if the snapshot changed since the last time we
1442 + // read from the store.
1443 if (checkIfSnapshotChanged(inst)) {
1444 // Force a re-render.
1445 forceStoreRerender(fiber);
1446 }
1339 - }, [subscribe, nextSnapshot, getSnapshot]);
1340 -
1341 - dispatcher.useEffect(() => {
1342 - const handleStoreChange = () => {
1343 - // TODO: Because there is no cross-renderer API for batching updates, it's
1344 - // up to the consumer of this library to wrap their subscription event
1345 - // with unstable_batchedUpdates. Should we try to detect when this isn't
1346 - // the case and print a warning in development?
1347 -
1348 - // The store changed. Check if the snapshot changed since the last time we
1349 - // read from the store.
1350 - if (checkIfSnapshotChanged(inst)) {
1351 - // Force a re-render.
1352 - forceStoreRerender(fiber);
1353 - }
1354 - };
1355 - // Check for changes right before subscribing. Subsequent changes will be
1356 - // detected in the subscription handler.
1357 - handleStoreChange();
1358 - // Subscribe to the store and return a clean-up function.
1359 - return subscribe(handleStoreChange);
1360 - }, [subscribe]);
1361 -
1362 - return nextSnapshot;
1447 + };
1448 + // Subscribe to the store and return a clean-up function.
1449 + return subscribe(handleStoreChange);
1450 }
1451
1452 function checkIfSnapshotChanged(inst) {
packages/react-reconciler/src/ReactFiberLane.new.js
+9 -10
@@ -453,27 +453,26 @@ export function includesOnlyTransitions(lanes: Lanes) {
453 return (lanes & TransitionLanes) === lanes;
454 }
455
456 -export function shouldTimeSlice(root: FiberRoot, lanes: Lanes) {
457 - if ((lanes & root.expiredLanes) !== NoLanes) {
458 - // At least one of these lanes expired. To prevent additional starvation,
459 - // finish rendering without yielding execution.
460 - return false;
461 - }
462 -
456 +export function includesBlockingLane(root: FiberRoot, lanes: Lanes) {
457 if (
458 allowConcurrentByDefault &&
459 (root.current.mode & ConcurrentUpdatesByDefaultMode) !== NoMode
460 ) {
461 // Concurrent updates by default always use time slicing.
468 - return true;
462 + return false;
463 }
470 -
464 const SyncDefaultLanes =
465 InputContinuousHydrationLane |
466 InputContinuousLane |
467 DefaultHydrationLane |
468 DefaultLane;
476 - return (lanes & SyncDefaultLanes) === NoLanes;
469 + return (lanes & SyncDefaultLanes) !== NoLanes;
470 +}
471 +
472 +export function includesExpiredLane(root: FiberRoot, lanes: Lanes) {
473 + // This is a separate check from includesBlockingLane because a lane can
474 + // expire after a render has already started.
475 + return (lanes & root.expiredLanes) !== NoLanes;
476 }
477
478 export function isTransitionLane(lane: Lane) {
packages/react-reconciler/src/ReactFiberLane.old.js
+9 -10
@@ -453,27 +453,26 @@ export function includesOnlyTransitions(lanes: Lanes) {
453 return (lanes & TransitionLanes) === lanes;
454 }
455
456 -export function shouldTimeSlice(root: FiberRoot, lanes: Lanes) {
457 - if ((lanes & root.expiredLanes) !== NoLanes) {
458 - // At least one of these lanes expired. To prevent additional starvation,
459 - // finish rendering without yielding execution.
460 - return false;
461 - }
462 -
456 +export function includesBlockingLane(root: FiberRoot, lanes: Lanes) {
457 if (
458 allowConcurrentByDefault &&
459 (root.current.mode & ConcurrentUpdatesByDefaultMode) !== NoMode
460 ) {
461 // Concurrent updates by default always use time slicing.
468 - return true;
462 + return false;
463 }
470 -
464 const SyncDefaultLanes =
465 InputContinuousHydrationLane |
466 InputContinuousLane |
467 DefaultHydrationLane |
468 DefaultLane;
476 - return (lanes & SyncDefaultLanes) === NoLanes;
469 + return (lanes & SyncDefaultLanes) !== NoLanes;
470 +}
471 +
472 +export function includesExpiredLane(root: FiberRoot, lanes: Lanes) {
473 + // This is a separate check from includesBlockingLane because a lane can
474 + // expire after a render has already started.
475 + return (lanes & root.expiredLanes) !== NoLanes;
476 }
477
478 export function isTransitionLane(lane: Lane) {
packages/react-reconciler/src/ReactFiberWorkLoop.new.js
+124 -28
@@ -13,6 +13,7 @@ import type {Lanes, Lane} from './ReactFiberLane.new';
13 import type {SuspenseState} from './ReactFiberSuspenseComponent.new';
14 import type {StackCursor} from './ReactFiberStack.new';
15 import type {Flags} from './ReactFiberFlags';
16 +import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
17
18 import {
19 warnAboutDeprecatedLifecycles,
@@ -34,6 +35,7 @@ import {
35 } from 'shared/ReactFeatureFlags';
36 import ReactSharedInternals from 'shared/ReactSharedInternals';
37 import invariant from 'shared/invariant';
38 +import is from 'shared/objectIs';
39
40 import {
41 // Aliased because `act` will override and push to an internal queue
@@ -116,6 +118,7 @@ import {
118 NoFlags,
119 Placement,
120 Incomplete,
121 + StoreConsistency,
122 HostEffectMask,
123 Hydrating,
124 BeforeMutationMask,
@@ -140,7 +143,8 @@ import {
143 includesNonIdleWork,
144 includesOnlyRetries,
145 includesOnlyTransitions,
143 - shouldTimeSlice,
146 + includesBlockingLane,
147 + includesExpiredLane,
148 getNextLanes,
149 markStarvedLanesAsExpired,
150 getLanesToRetrySynchronouslyOnError,
@@ -769,39 +773,25 @@ function performConcurrentWorkOnRoot(root, didTimeout) {
773 // TODO: We only check `didTimeout` defensively, to account for a Scheduler
774 // bug we're still investigating. Once the bug in Scheduler is fixed,
775 // we can remove this, since we track expiration ourselves.
772 - let exitStatus =
773 - shouldTimeSlice(root, lanes) &&
774 - (disableSchedulerTimeoutInWorkLoop || !didTimeout)
775 - ? renderRootConcurrent(root, lanes)
776 - : renderRootSync(root, lanes);
776 + const shouldTimeSlice =
777 + !includesBlockingLane(root, lanes) &&
778 + !includesExpiredLane(root, lanes) &&
779 + (disableSchedulerTimeoutInWorkLoop || !didTimeout);
780 + let exitStatus = shouldTimeSlice
781 + ? renderRootConcurrent(root, lanes)
782 + : renderRootSync(root, lanes);
783 if (exitStatus !== RootIncomplete) {
784 if (exitStatus === RootErrored) {
779 - const prevExecutionContext = executionContext;
780 - executionContext |= RetryAfterError;
781 -
782 - // If an error occurred during hydration,
783 - // discard server response and fall back to client side render.
784 - if (root.hydrate) {
785 - root.hydrate = false;
786 - if (__DEV__) {
787 - errorHydratingContainer(root.containerInfo);
788 - }
789 - clearContainer(root.containerInfo);
790 - }
791 -
792 - // If something threw an error, try rendering one more time. We'll render
793 - // synchronously to block concurrent data mutations, and we'll includes
794 - // all pending updates are included. If it still fails after the second
795 - // attempt, we'll give up and commit the resulting tree.
785 + // If something threw an error, try rendering one more time. We'll
786 + // render synchronously to block concurrent data mutations, and we'll
787 + // includes all pending updates are included. If it still fails after
788 + // the second attempt, we'll give up and commit the resulting tree.
789 const errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
790 if (errorRetryLanes !== NoLanes) {
791 lanes = errorRetryLanes;
799 - exitStatus = renderRootSync(root, errorRetryLanes);
792 + exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
793 }
801 -
802 - executionContext = prevExecutionContext;
794 }
804 -
795 if (exitStatus === RootFatalErrored) {
796 const fatalError = workInProgressRootFatalError;
797 prepareFreshStack(root, NoLanes);
@@ -810,9 +800,42 @@ function performConcurrentWorkOnRoot(root, didTimeout) {
800 throw fatalError;
801 }
802
803 + // Check if this render may have yielded to a concurrent event, and if so,
804 + // confirm that any newly rendered stores are consistent.
805 + // TODO: It's possible that even a concurrent render may never have yielded
806 + // to the main thread, if it was fast enough, or if it expired. We could
807 + // skip the consistency check in that case, too.
808 + const renderWasConcurrent = !includesBlockingLane(root, lanes);
809 + const finishedWork: Fiber = (root.current.alternate: any);
810 + if (
811 + renderWasConcurrent &&
812 + !isRenderConsistentWithExternalStores(finishedWork)
813 + ) {
814 + // A store was mutated in an interleaved event. Render again,
815 + // synchronously, to block further mutations.
816 + exitStatus = renderRootSync(root, lanes);
817 +
818 + // We need to check again if something threw
819 + if (exitStatus === RootErrored) {
820 + const errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
821 + if (errorRetryLanes !== NoLanes) {
822 + lanes = errorRetryLanes;
823 + exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
824 + // We assume the tree is now consistent because we didn't yield to any
825 + // concurrent events.
826 + }
827 + }
828 + if (exitStatus === RootFatalErrored) {
829 + const fatalError = workInProgressRootFatalError;
830 + prepareFreshStack(root, NoLanes);
831 + markRootSuspended(root, lanes);
832 + ensureRootIsScheduled(root, now());
833 + throw fatalError;
834 + }
835 + }
836 +
837 // We now have a consistent tree. The next step is either to commit it,
838 // or, if something suspended, wait to commit it after a timeout.
815 - const finishedWork: Fiber = (root.current.alternate: any);
839 root.finishedWork = finishedWork;
840 root.finishedLanes = lanes;
841 finishConcurrentRender(root, exitStatus, lanes);
@@ -827,6 +850,27 @@ function performConcurrentWorkOnRoot(root, didTimeout) {
850 return null;
851 }
852
853 +function recoverFromConcurrentError(root, errorRetryLanes) {
854 + const prevExecutionContext = executionContext;
855 + executionContext |= RetryAfterError;
856 +
857 + // If an error occurred during hydration, discard server response and fall
858 + // back to client side render.
859 + if (root.hydrate) {
860 + root.hydrate = false;
861 + if (__DEV__) {
862 + errorHydratingContainer(root.containerInfo);
863 + }
864 + clearContainer(root.containerInfo);
865 + }
866 +
867 + const exitStatus = renderRootSync(root, errorRetryLanes);
868 +
869 + executionContext = prevExecutionContext;
870 +
871 + return exitStatus;
872 +}
873 +
874 function finishConcurrentRender(root, exitStatus, lanes) {
875 switch (exitStatus) {
876 case RootIncomplete:
@@ -939,6 +983,58 @@ function finishConcurrentRender(root, exitStatus, lanes) {
983 }
984 }
985
986 +function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean {
987 + // Search the rendered tree for external store reads, and check whether the
988 + // stores were mutated in a concurrent event. Intentionally using a iterative
989 + // loop instead of recursion so we can exit early.
990 + let node: Fiber = finishedWork;
991 + while (true) {
992 + if (node.flags & StoreConsistency) {
993 + const updateQueue: FunctionComponentUpdateQueue | null = (node.updateQueue: any);
994 + if (updateQueue !== null) {
995 + const checks = updateQueue.stores;
996 + if (checks !== null) {
997 + for (let i = 0; i < checks.length; i++) {
998 + const check = checks[i];
999 + const getSnapshot = check.getSnapshot;
1000 + const renderedValue = check.value;
1001 + try {
1002 + if (!is(getSnapshot(), renderedValue)) {
1003 + // Found an inconsistent store.
1004 + return false;
1005 + }
1006 + } catch (error) {
1007 + // If `getSnapshot` throws, return `false`. This will schedule
1008 + // a re-render, and the error will be rethrown during render.
1009 + return false;
1010 + }
1011 + }
1012 + }
1013 + }
1014 + }
1015 + const child = node.child;
1016 + if (node.subtreeFlags & StoreConsistency && child !== null) {
1017 + child.return = node;
1018 + node = child;
1019 + continue;
1020 + }
1021 + if (node === finishedWork) {
1022 + return true;
1023 + }
1024 + while (node.sibling === null) {
1025 + if (node.return === null || node.return === finishedWork) {
1026 + return true;
1027 + }
1028 + node = node.return;
1029 + }
1030 + node.sibling.return = node.return;
1031 + node = node.sibling;
1032 + }
1033 + // Flow doesn't know this is unreachable, but eslint does
1034 + // eslint-disable-next-line no-unreachable
1035 + return true;
1036 +}
1037 +
1038 function markRootSuspended(root, suspendedLanes) {
1039 // When suspending, we should always exclude lanes that were pinged or (more
1040 // rarely, since we try to avoid it) updated during the render phase.
packages/react-reconciler/src/ReactFiberWorkLoop.old.js
+124 -28
@@ -13,6 +13,7 @@ import type {Lanes, Lane} from './ReactFiberLane.old';
13 import type {SuspenseState} from './ReactFiberSuspenseComponent.old';
14 import type {StackCursor} from './ReactFiberStack.old';
15 import type {Flags} from './ReactFiberFlags';
16 +import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.old';
17
18 import {
19 warnAboutDeprecatedLifecycles,
@@ -34,6 +35,7 @@ import {
35 } from 'shared/ReactFeatureFlags';
36 import ReactSharedInternals from 'shared/ReactSharedInternals';
37 import invariant from 'shared/invariant';
38 +import is from 'shared/objectIs';
39
40 import {
41 // Aliased because `act` will override and push to an internal queue
@@ -116,6 +118,7 @@ import {
118 NoFlags,
119 Placement,
120 Incomplete,
121 + StoreConsistency,
122 HostEffectMask,
123 Hydrating,
124 BeforeMutationMask,
@@ -140,7 +143,8 @@ import {
143 includesNonIdleWork,
144 includesOnlyRetries,
145 includesOnlyTransitions,
143 - shouldTimeSlice,
146 + includesBlockingLane,
147 + includesExpiredLane,
148 getNextLanes,
149 markStarvedLanesAsExpired,
150 getLanesToRetrySynchronouslyOnError,
@@ -769,39 +773,25 @@ function performConcurrentWorkOnRoot(root, didTimeout) {
773 // TODO: We only check `didTimeout` defensively, to account for a Scheduler
774 // bug we're still investigating. Once the bug in Scheduler is fixed,
775 // we can remove this, since we track expiration ourselves.
772 - let exitStatus =
773 - shouldTimeSlice(root, lanes) &&
774 - (disableSchedulerTimeoutInWorkLoop || !didTimeout)
775 - ? renderRootConcurrent(root, lanes)
776 - : renderRootSync(root, lanes);
776 + const shouldTimeSlice =
777 + !includesBlockingLane(root, lanes) &&
778 + !includesExpiredLane(root, lanes) &&
779 + (disableSchedulerTimeoutInWorkLoop || !didTimeout);
780 + let exitStatus = shouldTimeSlice
781 + ? renderRootConcurrent(root, lanes)
782 + : renderRootSync(root, lanes);
783 if (exitStatus !== RootIncomplete) {
784 if (exitStatus === RootErrored) {
779 - const prevExecutionContext = executionContext;
780 - executionContext |= RetryAfterError;
781 -
782 - // If an error occurred during hydration,
783 - // discard server response and fall back to client side render.
784 - if (root.hydrate) {
785 - root.hydrate = false;
786 - if (__DEV__) {
787 - errorHydratingContainer(root.containerInfo);
788 - }
789 - clearContainer(root.containerInfo);
790 - }
791 -
792 - // If something threw an error, try rendering one more time. We'll render
793 - // synchronously to block concurrent data mutations, and we'll includes
794 - // all pending updates are included. If it still fails after the second
795 - // attempt, we'll give up and commit the resulting tree.
785 + // If something threw an error, try rendering one more time. We'll
786 + // render synchronously to block concurrent data mutations, and we'll
787 + // includes all pending updates are included. If it still fails after
788 + // the second attempt, we'll give up and commit the resulting tree.
789 const errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
790 if (errorRetryLanes !== NoLanes) {
791 lanes = errorRetryLanes;
799 - exitStatus = renderRootSync(root, errorRetryLanes);
792 + exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
793 }
801 -
802 - executionContext = prevExecutionContext;
794 }
804 -
795 if (exitStatus === RootFatalErrored) {
796 const fatalError = workInProgressRootFatalError;
797 prepareFreshStack(root, NoLanes);
@@ -810,9 +800,42 @@ function performConcurrentWorkOnRoot(root, didTimeout) {
800 throw fatalError;
801 }
802
803 + // Check if this render may have yielded to a concurrent event, and if so,
804 + // confirm that any newly rendered stores are consistent.
805 + // TODO: It's possible that even a concurrent render may never have yielded
806 + // to the main thread, if it was fast enough, or if it expired. We could
807 + // skip the consistency check in that case, too.
808 + const renderWasConcurrent = !includesBlockingLane(root, lanes);
809 + const finishedWork: Fiber = (root.current.alternate: any);
810 + if (
811 + renderWasConcurrent &&
812 + !isRenderConsistentWithExternalStores(finishedWork)
813 + ) {
814 + // A store was mutated in an interleaved event. Render again,
815 + // synchronously, to block further mutations.
816 + exitStatus = renderRootSync(root, lanes);
817 +
818 + // We need to check again if something threw
819 + if (exitStatus === RootErrored) {
820 + const errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
821 + if (errorRetryLanes !== NoLanes) {
822 + lanes = errorRetryLanes;
823 + exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
824 + // We assume the tree is now consistent because we didn't yield to any
825 + // concurrent events.
826 + }
827 + }
828 + if (exitStatus === RootFatalErrored) {
829 + const fatalError = workInProgressRootFatalError;
830 + prepareFreshStack(root, NoLanes);
831 + markRootSuspended(root, lanes);
832 + ensureRootIsScheduled(root, now());
833 + throw fatalError;
834 + }
835 + }
836 +
837 // We now have a consistent tree. The next step is either to commit it,
838 // or, if something suspended, wait to commit it after a timeout.
815 - const finishedWork: Fiber = (root.current.alternate: any);
839 root.finishedWork = finishedWork;
840 root.finishedLanes = lanes;
841 finishConcurrentRender(root, exitStatus, lanes);
@@ -827,6 +850,27 @@ function performConcurrentWorkOnRoot(root, didTimeout) {
850 return null;
851 }
852
853 +function recoverFromConcurrentError(root, errorRetryLanes) {
854 + const prevExecutionContext = executionContext;
855 + executionContext |= RetryAfterError;
856 +
857 + // If an error occurred during hydration, discard server response and fall
858 + // back to client side render.
859 + if (root.hydrate) {
860 + root.hydrate = false;
861 + if (__DEV__) {
862 + errorHydratingContainer(root.containerInfo);
863 + }
864 + clearContainer(root.containerInfo);
865 + }
866 +
867 + const exitStatus = renderRootSync(root, errorRetryLanes);
868 +
869 + executionContext = prevExecutionContext;
870 +
871 + return exitStatus;
872 +}
873 +
874 function finishConcurrentRender(root, exitStatus, lanes) {
875 switch (exitStatus) {
876 case RootIncomplete:
@@ -939,6 +983,58 @@ function finishConcurrentRender(root, exitStatus, lanes) {
983 }
984 }
985
986 +function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean {
987 + // Search the rendered tree for external store reads, and check whether the
988 + // stores were mutated in a concurrent event. Intentionally using a iterative
989 + // loop instead of recursion so we can exit early.
990 + let node: Fiber = finishedWork;
991 + while (true) {
992 + if (node.flags & StoreConsistency) {
993 + const updateQueue: FunctionComponentUpdateQueue | null = (node.updateQueue: any);
994 + if (updateQueue !== null) {
995 + const checks = updateQueue.stores;
996 + if (checks !== null) {
997 + for (let i = 0; i < checks.length; i++) {
998 + const check = checks[i];
999 + const getSnapshot = check.getSnapshot;
1000 + const renderedValue = check.value;
1001 + try {
1002 + if (!is(getSnapshot(), renderedValue)) {
1003 + // Found an inconsistent store.
1004 + return false;
1005 + }
1006 + } catch (error) {
1007 + // If `getSnapshot` throws, return `false`. This will schedule
1008 + // a re-render, and the error will be rethrown during render.
1009 + return false;
1010 + }
1011 + }
1012 + }
1013 + }
1014 + }
1015 + const child = node.child;
1016 + if (node.subtreeFlags & StoreConsistency && child !== null) {
1017 + child.return = node;
1018 + node = child;
1019 + continue;
1020 + }
1021 + if (node === finishedWork) {
1022 + return true;
1023 + }
1024 + while (node.sibling === null) {
1025 + if (node.return === null || node.return === finishedWork) {
1026 + return true;
1027 + }
1028 + node = node.return;
1029 + }
1030 + node.sibling.return = node.return;
1031 + node = node.sibling;
1032 + }
1033 + // Flow doesn't know this is unreachable, but eslint does
1034 + // eslint-disable-next-line no-unreachable
1035 + return true;
1036 +}
1037 +
1038 function markRootSuspended(root, suspendedLanes) {
1039 // When suspending, we should always exclude lanes that were pinged or (more
1040 // rarely, since we try to avoid it) updated during the render phase.
packages/react-reconciler/src/__tests__/useSyncExternalStore-test.js new
+177
@@ -0,0 +1,177 @@
1 +/**
2 + * Copyright (c) Facebook, Inc. and its affiliates.
3 + *
4 + * This source code is licensed under the MIT license found in the
5 + * LICENSE file in the root directory of this source tree.
6 + *
7 + * @emails react-core
8 + */
9 +
10 +'use strict';
11 +
12 +let useSyncExternalStore;
13 +let React;
14 +let ReactNoop;
15 +let Scheduler;
16 +let act;
17 +let useLayoutEffect;
18 +let forwardRef;
19 +let useImperativeHandle;
20 +let useRef;
21 +let startTransition;
22 +
23 +// This tests the native useSyncExternalStore implementation, not the shim.
24 +// Tests that apply to both the native implementation and the shim should go
25 +// into useSyncExternalStoreShared-test.js. The reason they are separate is
26 +// because at some point we may start running the shared tests against vendored
27 +// React DOM versions (16, 17, etc) instead of React Noop.
28 +describe('useSyncExternalStore', () => {
29 + beforeEach(() => {
30 + jest.resetModules();
31 +
32 + React = require('react');
33 + ReactNoop = require('react-noop-renderer');
34 + Scheduler = require('scheduler');
35 + useLayoutEffect = React.useLayoutEffect;
36 + useImperativeHandle = React.useImperativeHandle;
37 + forwardRef = React.forwardRef;
38 + useRef = React.useRef;
39 + useSyncExternalStore = React.unstable_useSyncExternalStore;
40 + startTransition = React.startTransition;
41 +
42 + act = require('jest-react').act;
43 + });
44 +
45 + function Text({text}) {
46 + Scheduler.unstable_yieldValue(text);
47 + return text;
48 + }
49 +
50 + function createExternalStore(initialState) {
51 + const listeners = new Set();
52 + let currentState = initialState;
53 + return {
54 + set(text) {
55 + currentState = text;
56 + ReactNoop.batchedUpdates(() => {
57 + listeners.forEach(listener => listener());
58 + });
59 + },
60 + subscribe(listener) {
61 + listeners.add(listener);
62 + return () => listeners.delete(listener);
63 + },
64 + getState() {
65 + return currentState;
66 + },
67 + getSubscriberCount() {
68 + return listeners.size;
69 + },
70 + };
71 + }
72 +
73 + // @gate supportsNativeUseSyncExternalStore
74 + test(
75 + 'detects interleaved mutations during a concurrent read before ' +
76 + 'layout effects fire',
77 + async () => {
78 + const store1 = createExternalStore(0);
79 + const store2 = createExternalStore(0);
80 +
81 + const Child = forwardRef(({store, label}, ref) => {
82 + const value = useSyncExternalStore(store.subscribe, store.getState);
83 + useImperativeHandle(
84 + ref,
85 + () => {
86 + return value;
87 + },
88 + [],
89 + );
90 + return <Text text={label + value} />;
91 + });
92 +
93 + function App({store}) {
94 + const refA = useRef(null);
95 + const refB = useRef(null);
96 + const refC = useRef(null);
97 + useLayoutEffect(() => {
98 + // This layout effect reads children that depend on an external store.
99 + // This demostrates whether the children are consistent when the
100 + // layout phase runs.
101 + const aText = refA.current;
102 + const bText = refB.current;
103 + const cText = refC.current;
104 + Scheduler.unstable_yieldValue(
105 + `Children observed during layout: A${aText}B${bText}C${cText}`,
106 + );
107 + });
108 + return (
109 + <>
110 + <Child store={store} ref={refA} label="A" />
111 + <Child store={store} ref={refB} label="B" />
112 + <Child store={store} ref={refC} label="C" />
113 + </>
114 + );
115 + }
116 +
117 + const root = ReactNoop.createRoot();
118 + await act(async () => {
119 + // Start a concurrent render that reads from the store, then yield.
120 + startTransition(() => {
121 + root.render(<App store={store1} />);
122 + });
123 +
124 + expect(Scheduler).toFlushAndYieldThrough(['A0', 'B0']);
125 +
126 + // During an interleaved event, the store is mutated.
127 + store1.set(1);
128 +
129 + // Then we continue rendering.
130 + expect(Scheduler).toFlushAndYield([
131 + // C reads a newer value from the store than A or B, which means they
132 + // are inconsistent.
133 + 'C1',
134 +
135 + // Before committing the layout effects, React detects that the store
136 + // has been mutated. So it throws out the entire completed tree and
137 + // re-renders the new values.
138 + 'A1',
139 + 'B1',
140 + 'C1',
141 + // The layout effects reads consistent children.
142 + 'Children observed during layout: A1B1C1',
143 + ]);
144 + });
145 +
146 + // Now we're going test the same thing during an update that
147 + // switches stores.
148 + await act(async () => {
149 + startTransition(() => {
150 + root.render(<App store={store2} />);
151 + });
152 +
153 + // Start a concurrent render that reads from the store, then yield.
154 + expect(Scheduler).toFlushAndYieldThrough(['A0', 'B0']);
155 +
156 + // During an interleaved event, the store is mutated.
157 + store2.set(1);
158 +
159 + // Then we continue rendering.
160 + expect(Scheduler).toFlushAndYield([
161 + // C reads a newer value from the store than A or B, which means they
162 + // are inconsistent.
163 + 'C1',
164 +
165 + // Before committing the layout effects, React detects that the store
166 + // has been mutated. So it throws out the entire completed tree and
167 + // re-renders the new values.
168 + 'A1',
169 + 'B1',
170 + 'C1',
171 + // The layout effects reads consistent children.
172 + 'Children observed during layout: A1B1C1',
173 + ]);
174 + });
175 + },
176 + );
177 +});
scripts/jest/TestFlags.js
+4
@@ -84,6 +84,10 @@ function getTestFlags() {
84 source: !process.env.IS_BUILD,
85 www,
86
87 + // This isn't a flag, just a useful alias for tests. Remove once
88 + // useSyncExternalStore lands in the `next` channel.
89 + supportsNativeUseSyncExternalStore: __EXPERIMENTAL__ || www,
90 +
91 // If there's a naming conflict between scheduler and React feature flags, the
92 // React ones take precedence.
93 // TODO: Maybe we should error on conflicts? Or we could namespace