useSyncExternalStore
Subscribes to an external store in a concurrent-safe way.
Syntax
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
subscribe | function | Yes | Takes a callback, subscribes to the store, and returns an unsubscribe function. |
getSnapshot | function | Yes | Returns the current store snapshot; must return a cached, stable value. |
getServerSnapshot | function | No | Returns the snapshot used during server rendering and hydration. |
Returns
any — The current snapshot of the external store.
Examples
function useOnline() {
return useSyncExternalStore(
(cb) => {
window.addEventListener('online', cb);
window.addEventListener('offline', cb);
return () => {
window.removeEventListener('online', cb);
window.removeEventListener('offline', cb);
};
},
() => navigator.onLine,
() => true
);
}
Notes
Intended for library authors integrating non-React stores so reads stay
consistent with concurrent rendering. getSnapshot must return a referentially
stable value, returning a cached object when nothing changed, to avoid
infinite re-renders. Provide getServerSnapshot for SSR support.