Jun-16, 2025 · 3min
change languageLearn how to use the React useSyncExternalStore hook to implement network status monitoring, creating a reliable online status detection component
import { useSyncExternalStore } from 'react'
function getSnapshot() {
return navigator.onLine
}
function getServerSnapshot() {
return true
}
function subscribe(onStoreChange: () => void) {
window.addEventListener('online', onStoreChange)
window.addEventListener('offline', onStoreChange)
return () => {
window.removeEventListener('online', onStoreChange)
window.removeEventListener('offline', onStoreChange)
}
}
export function useIsOnline() {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
}Each time the subscribe onStoreChange function is executed, it will execute getSnapshot to get the latest value, triggering rendering
getSnapshot returns an immutable value each time
getServerSnapshot is the value initialized in server-side rendering
Official documentation useSyncExternalStore