@@ -405,43 +405,43 @@ If your store data is mutable, your `getSnapshot` function should return an immu
405
405
406
406
This ` subscribe` function is defined *inside* a component so it is different on every re-render:
407
407
408
- ` ` ` js {4 - 7 }
408
+ ` ` ` js {2 - 5 }
409
409
function ChatIndicator () {
410
- const isOnline = useSyncExternalStore (subscribe, getSnapshot);
411
-
412
410
// 🚩 Always a different function, so React will resubscribe on every re-render
413
411
function subscribe () {
414
412
// ...
415
413
}
414
+
415
+ const isOnline = useSyncExternalStore (subscribe, getSnapshot);
416
416
417
417
// ...
418
418
}
419
419
` ` `
420
420
421
421
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:
422
422
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 () {
426
426
// ...
427
427
}
428
428
429
- // ✅ Always the same function, so React won't need to resubscribe
430
- function subscribe () {
429
+ function ChatIndicator () {
430
+ const isOnline = useSyncExternalStore (subscribe, getSnapshot);
431
431
// ...
432
432
}
433
433
` ` `
434
434
435
435
Alternatively, wrap ` subscribe` into [` useCallback` ](/reference/react/useCallback) to only resubscribe when some argument changes:
436
436
437
- ` ` ` js {4 - 8 }
437
+ ` ` ` js {2 - 5 }
438
438
function ChatIndicator ({ userId }) {
439
- const isOnline = useSyncExternalStore (subscribe, getSnapshot);
440
-
441
439
// ✅ Same function as long as userId doesn't change
442
440
const subscribe = useCallback (() => {
443
441
// ...
444
442
}, [userId]);
443
+
444
+ const isOnline = useSyncExternalStore (subscribe, getSnapshot);
445
445
446
446
// ...
447
447
}
0 commit comments