Skip to content

Commit e9918cf

Browse files
authored
[18] Add docs for useSyncExternalStore (#4487)
* [18] Add docs for useSyncExternalStore * rm "optional"
1 parent e5eb8ca commit e9918cf

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

content/docs/hooks-reference.md

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -550,14 +550,48 @@ The following Hooks are provided for library authors to integrate libraries deep
550550
### `useSyncExternalStore` {#usesyncexternalstore}
551551

552552
```js
553-
const state = useSyncExternalStore(subscribe, snapshot);
553+
const state = useSyncExternalStore(subscribe, getSnapshot[, getServerSnapshot]);
554554
```
555555

556-
TODO: description
556+
`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:
564+
565+
```js
566+
const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
567+
```
568+
569+
However, you can also subscribe to a specific field:
570+
571+
```js
572+
const selectedField = 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+
const selectedField = useSyncExternalStore(
582+
store.subscribe,
583+
() => store.getSnapshot().selectedField,
584+
() => INITIAL_SERVER_SNAPSHOT.selectedField,
585+
);
586+
```
557587

558588
> Note:
559589
>
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`.
561595
562596
### `useInsertionEffect` {#useinsertioneffect}
563597

0 commit comments

Comments
 (0)