javascript / intermediate
Snippet
Subscribing to External Data with useSyncExternalStore
This hook is the recommended way to subscribe to external data sources (like browser APIs or non-React stores) in a way that is compatible with React's concurrent rendering.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
import { useSyncExternalStore } from 'react';const isOnline = useSyncExternalStore((onStoreChange) => {window.addEventListener('online', onStoreChange);window.addEventListener('offline', onStoreChange);return () => {window.removeEventListener('online', onStoreChange);window.removeEventListener('offline', onStoreChange);};},() => navigator.onLine);
react
Breakdown
1
useSyncExternalStore(subscribe, getSnapshot)
Accepts a subscription function and a function to retrieve the current value from the external source.