React 应用有时需要读取已有的事件总线、浏览器在线状态或非 React 状态容器。直接在 render 中读取可变对象,可能在并发渲染时看到不一致的值。useSyncExternalStore 提供标准订阅和快照接口。本文以连接状态与消息计数为例说明正确的集成方式。
1. 先区分内部状态与外部状态
如果数据完全属于单个 React 组件,useState 通常就足够了。只有状态由 React 之外的系统持有,且组件需要持续读取它时,才考虑这个 Hook。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/690f209d77c4b377f85c70fd81fbe6842ab0b57f">
<section><h2>连接中心</h2><p>显示通信状态与未读消息数</p></section>
</div>
2. 实现稳定的外部快照
getSnapshot 返回的是当前数据视图。没有数据变化时必须返回相同的对象引用,而不是每次调用都创建一个新对象。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/115366d0e61d87541a12f1b18745079ac292f282">
<output aria-label="未读消息数">{snapshot.unread}</output>
</div>
type Snapshot = Readonly<{
online: boolean; unread: number }>;
let snapshot: Snapshot = Object.freeze({
online: true, unread: 0 });
const listeners = new Set<() => void>();
export const getSnapshot = () => snapshot;
export function update(next: Snapshot) {
if (next.online === snapshot.online && next.unread === snapshot.unread) return;
snapshot = Object.freeze({
...next });
listeners.forEach(listener => listener());
}
3. 订阅函数必须提供清理
subscribe 接收通知回调并返回取消订阅函数。定义在组件外部可保持函数身份稳定,减少不必要的重新订阅。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/742516d897a5e67cb7271a8f575fc6e0fe3056b4">
<p role="status">{snapshot.online ? '在线' : '离线'}</p>
</div>
export function subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener); };
}
4. 在 React 组件中读取快照
Hook 负责协调订阅与快照读取,组件不需要再维护一份通过 effect 同步的本地副本。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
<section aria-label="消息摘要">
<span>未读:{snapshot.unread}</span>
<span>{snapshot.online ? '可用' : '断开'}</span>
</section>
</div>
import { useSyncExternalStore } from 'react';
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
5. 适配浏览器在线状态
navigator.onLine 表示浏览器判断的网络连接状态,不代表业务服务必然可达。应单独记录业务连接探测结果。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b3b4fcbc146dd1ed3ab4df1254f6c98582be52b3">
<p role="status">{online ? '设备有网络连接' : '设备离线'}</p>
</div>
function subscribeOnline(notify: () => void) {
window.addEventListener('online', notify);
window.addEventListener('offline', notify);
return () => {
window.removeEventListener('online', notify);
window.removeEventListener('offline', notify);
};
}
const readOnline = () => navigator.onLine;
6. 服务器渲染时的初始快照
getServerSnapshot 在服务端及客户端水合阶段提供初始数据。两端必须一致。若每个用户有不同的初始数据,需要通过请求作用域和序列化机制传递,不能共享全局私人状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4e61fb1b816f56cbfc14d974992112e3abe20a43">
<aside aria-label="初始连接信息"><span>连接状态将在客户端更新</span></aside>
</div>
const initialSnapshot = Object.freeze({
online: true, unread: 0 });
const getServerSnapshot = () => initialSnapshot;
7. 避免无意义的整体更新
当数据对象拥有大量字段时,一个新快照可能触发所有相关订阅者重新读取。拆分业务独立的状态容器,或使用具备选择器能力的成熟实现。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
<section><h2>未读消息</h2><strong>{unread}</strong></section>
</div>
const getUnread = () => getSnapshot().unread;
const getServerUnread = () => getServerSnapshot().unread;
const unread = useSyncExternalStore(subscribe, getUnread, getServerUnread);
8. 确保外部事件有明确的状态所有者
消息到达后由外部 store 更新,不要在每个订阅组件中分别增加计数。否则多组件挂载可能让同一事件被重复计算。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/5de111f3a6f0157e24507ff84a74e361871d8be2">
<button type="button" onClick={markAllRead}>全部标记已读</button>
</div>
function markAllRead() {
update({
...getSnapshot(), unread: 0 });
}
9. 外部事件与业务连接分离
WebSocket 或事件流适配器应独立处理重连、心跳和错误恢复,store 仅接收已规范化的数据。订阅组件并不负责创建每个连接实例。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c4d40e68ab325d4ea2cb67f1d4cf853bcc66f3f6">
<dl><dt>连接状态</dt><dd>{connectionState}</dd><dt>消息数</dt><dd>{snapshot.unread}</dd></dl>
</div>
外部事件可能乱序或重复,业务数据仍需稳定 ID、版本或服务端确认。Hook 本身不会自动处理这些协议问题。
10. 验证快照和清理行为
测试没有变化时快照引用相同,有变化时引用不同;订阅取消后回调不再执行。React 组件测试还应覆盖挂载与卸载。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff3614ed36c1ebaeabd92a47ed560eed4799e07a">
<p aria-live="polite">{snapshot.unread === 0 ? '没有未读消息' : '存在新消息'}</p>
</div>
const before = getSnapshot();
update({
...before });
expect(getSnapshot()).toBe(before);
const callback = vi.fn();
const stop = subscribe(callback);
stop();
update({
...before, unread: before.unread + 1 });
expect(callback).not.toHaveBeenCalled();
总结
useSyncExternalStore 解决的是 React 与外部可变数据源之间的读取一致性。正确的实现依赖稳定快照、可清理的订阅和合理的状态边界,而不是简单地将每次外部变化复制到组件内部。