You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`useSyncExternalStore` is a hook recommended for reading and subscribing from external data sources in a way that's compatible with concurrent rendering features like selective hydration and time slicing.
557
+
558
+
This method returns the value of the store and accepts three arguments:
559
+
-`subscribe`: function to register a callback that is called whenever the store changes.
560
+
-`getSnapshot`: function that returns the current value of the store.
561
+
-`getServerSnapshot`: function that returns the snapshot used during server rendering.
562
+
563
+
The most basic example simply subscribes to the entire store:
However, you can also subscribe to a specific field:
570
+
571
+
```js
572
+
constselectedField=useSyncExternalStore(
573
+
store.subscribe,
574
+
() =>store.getSnapshot().selectedField,
575
+
);
576
+
```
577
+
578
+
When server rendering, you must serialize the store value used on the server, and provide it to `useSyncExternalStore`. React will use this snapshot during hydration to prevent server mismatches:
579
+
580
+
```js
581
+
constselectedField=useSyncExternalStore(
582
+
store.subscribe,
583
+
() =>store.getSnapshot().selectedField,
584
+
() =>INITIAL_SERVER_SNAPSHOT.selectedField,
585
+
);
586
+
```
557
587
558
588
> Note:
559
589
>
560
-
> TODO: use-sync-external-store/shim
590
+
> `getSnapshot` must return a cached value. If getSnapshot is called multiple times in a row, it must return the same exact value unless there was a store update in between.
591
+
>
592
+
> A shim is provided for supporting multiple React versions published as `use-sync-external-store/shim`. This shim will prefer `useSyncExternalStore` when available, and fallback to a user-space implementation when it's not.
593
+
>
594
+
> As a convenience, we also provide a version of the API with automatic support for memoizing the result of getSnapshot published as `use-sync-external-store/with-selector`.
0 commit comments