javascript / expert
Snippet
Synchronizing External Stores with useSyncExternalStore
The useSyncExternalStore hook is the recommended way to subscribe to external data sources (like browser APIs or global state managers) in a way that is compatible with React's concurrent rendering. It prevents 'tearing', where different components see different values for the same state during a single render cycle.
snippet.js
javascript
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 networkStore = {subscribe(callback) {window.addEventListener('online', callback);window.addEventListener('offline', callback);return () => {window.removeEventListener('online', callback);window.removeEventListener('offline', callback);};},getSnapshot() {return navigator.onLine;}};function useNetworkStatus() {return useSyncExternalStore(networkStore.subscribe,networkStore.getSnapshot);}
react
Breakdown
1
subscribe(callback) { ... }
Registers a listener and returns a cleanup function to prevent memory leaks.
2
getSnapshot() { ... }
Returns a stable, immutable snapshot of the current state from the external source.
3
useSyncExternalStore(...)
The hook ensures the component re-renders only when the snapshot changes, maintaining consistency.