Skip to content

Commit b5c16dc

Browse files
authored
fix(reference): declare subscribe before passing it to the hook (#7711)
1 parent b77c05d commit b5c16dc

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

src/content/reference/react/useSyncExternalStore.md

+11-11
Original file line numberDiff line numberDiff line change
@@ -405,43 +405,43 @@ If your store data is mutable, your `getSnapshot` function should return an immu
405405
406406
This `subscribe` function is defined *inside* a component so it is different on every re-render:
407407
408-
```js {4-7}
408+
```js {2-5}
409409
function ChatIndicator() {
410-
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
411-
412410
// 🚩 Always a different function, so React will resubscribe on every re-render
413411
function subscribe() {
414412
// ...
415413
}
414+
415+
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
416416

417417
// ...
418418
}
419419
```
420420
421421
React will resubscribe to your store if you pass a different `subscribe` function between re-renders. If this causes performance issues and you'd like to avoid resubscribing, move the `subscribe` function outside:
422422
423-
```js {6-9}
424-
function ChatIndicator() {
425-
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
423+
```js {1-4}
424+
// ✅ Always the same function, so React won't need to resubscribe
425+
function subscribe() {
426426
// ...
427427
}
428428

429-
// ✅ Always the same function, so React won't need to resubscribe
430-
function subscribe() {
429+
function ChatIndicator() {
430+
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
431431
// ...
432432
}
433433
```
434434
435435
Alternatively, wrap `subscribe` into [`useCallback`](/reference/react/useCallback) to only resubscribe when some argument changes:
436436
437-
```js {4-8}
437+
```js {2-5}
438438
function ChatIndicator({ userId }) {
439-
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
440-
441439
// ✅ Same function as long as userId doesn't change
442440
const subscribe = useCallback(() => {
443441
// ...
444442
}, [userId]);
443+
444+
const isOnline = useSyncExternalStore(subscribe, getSnapshot);
445445

446446
// ...
447447
}

0 commit comments

Comments
 (0)