javascript / expert
Snippet
External Store Sync with useSyncExternalStore
useSyncExternalStore is the recommended way to subscribe to external data sources. It prevents 'tearing' in concurrent rendering by ensuring the UI stays consistent with the store.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { useSyncExternalStore } from 'react';const store = {value: 0,listeners: new Set<() => void>(),subscribe(callback: () => void) {this.listeners.add(callback);return () => this.listeners.delete(callback);},getSnapshot() {return this.value;},increment() {this.value++;this.listeners.forEach(l => l());}};function ExternalCounter() {const value = useSyncExternalStore(store.subscribe, store.getSnapshot);return <button onClick={() => store.increment()}>{value}</button>;}
react
Breakdown
1
useSyncExternalStore(store.subscribe, store.getSnapshot)
Hooks into the store's subscription mechanism and retrieves the current value.
2
getSnapshot() { return this.value; }
Returns the current state of the store; must return the same value if the store hasn't changed.