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) in Next.js/React. It ensures 'tearing' is avoided during concurrent rendering and provides a consistent snapshot of the data, including support for Server-Side Rendering (SSR) via the getServerSnapshot argument.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { useSyncExternalStore } from 'react';const subscribe = (callback) => {window.addEventListener('online', callback);window.addEventListener('offline', callback);return () => {window.removeEventListener('online', callback);window.removeEventListener('offline', callback);};};const getSnapshot = () => navigator.onLine;const getServerSnapshot = () => true;function useOnlineStatus() {return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);}
nextjs
Breakdown
1
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
Connects an external store to React, handling subscription and snapshot consistency.
2
const subscribe = (callback) => { ... };
A function that registers a listener and returns a cleanup function to unsubscribe.
3
const getSnapshot = () => navigator.onLine;
Returns the current value of the external state used for rendering.