使用 useSyncExternalStore 实现 useIsOnline

Jun-16, 2025 · 3min

change language

学习如何使用 React 的 useSyncExternalStore hook 实现网络状态监听,创建可靠的在线状态检测组件

use-is-online.ts
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)
}

每次 subscribeonStoreChange 函数执行的时候都会执行一遍 getSnapshot 获取一遍最新的值,触发渲染

getSnapshot 每次返回一个不可变的值

getServerSnapshot 在服务端渲染初始化的值

官方文档 useSyncExternalStore

'use client'
import { useIsOnline } from './use-is-online'

export default function Page() {
  const isOnline = useIsOnline()

  return (
    <div>
      <h1>{isOnline ? '✅ Online' : '❌ Disconnected'}</h1>
    </div>
  )
}