Jun-16, 2025 · 3min
change language学习如何使用 React 的 useSyncExternalStore hook 实现网络状态监听,创建可靠的在线状态检测组件
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)
}
每次 subscribe
的 onStoreChange
函数执行的时候都会执行一遍 getSnapshot
获取一遍最新的值,触发渲染
getSnapshot
每次返回一个不可变的值
getServerSnapshot
在服务端渲染初始化的值
官方文档 useSyncExternalStore