javascript / expert
Snippet
Subscribing to External Stores with useSyncExternalStore
The useSyncExternalStore hook is the recommended way to subscribe to external data sources in React 18+. It prevents 'tearing' in concurrent rendering by ensuring the UI stays in sync with the external state during the entire render cycle, which standard useEffect patterns cannot guarantee.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const store = {state: { count: 0 },listeners: new Set(),subscribe(cb) {this.listeners.add(cb);return () => this.listeners.delete(cb);},getSnapshot() { return this.state; },increment() {this.state = { count: this.state.count + 1 };this.listeners.forEach(l => l());}};function useExternalCounter() {return useSyncExternalStore(store.subscribe.bind(store),store.getSnapshot.bind(store));}
react
Breakdown
1
subscribe(cb) { ... }
Registers a callback that the store calls whenever the state changes.
2
getSnapshot() { ... }
Returns the current value of the store; must return the same value if the store hasn't changed.
3
useSyncExternalStore(...)
Subscribes to the store and returns the snapshot, triggering a re-render only when the snapshot changes.