Subscribe to an external store with useSyncExternalStore
Read a value that lives outside React, such as navigator.onLine, with useSyncExternalStore so renders stay consistent and the server can render too.
Browser state like network status changes outside React. Copying it into state with an effect can show a stale value for a render, while useSyncExternalStore reads it safely during render.
import { useSyncExternalStore } from 'react';
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true,
);
}import { useOnlineStatus } from './useOnlineStatus.js';
export function StatusBar() {
const isOnline = useOnlineStatus();
return <p>{isOnline ? '✅ Online' : '❌ Disconnected'}</p>;
}✅ Online (connected)
❌ Disconnected (after the browser fires "offline")The three arguments are how to subscribe, how to read the current value in the browser, and what to assume on the server. React calls the snapshot function on every render and compares with Object.is, so it must return the same value when nothing changed. A fresh object each time causes an infinite loop. See useSyncExternalStore.
For state that lives in React, useState is the right tool, not this hook.