TSX
Public
Online Status with useSyncExternalStore
Subscribe to the browser online state through React useSyncExternalStore.
#react
#hooks
#state
#browser-api
TSX
'use client';
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
function getSnapshot() {
return navigator.onLine;
}
function getServerSnapshot() {
return true;
}
export function OnlineStatus() {
const isOnline = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
return (
<span role="status">
{isOnline ? 'Online' : 'Offline'}
</span>
);
}