当前位置: 首页 > news >正文

React中的useSyncExternalStore使用

官方的解释是useSyncExternalStore 是一个让你订阅外部 store 的 React Hook。😄官方就爱打马虎眼,这样说随能一下子明白它的作用,接下来我们就来仔细的讲解下它的作用和应用场景。

useSyncExternalStore 作为 React 18 引入的一个 Hook,主要用于订阅外部数据源,确保在并发渲染下数据的一致性。它主要用于:

  • 订阅浏览器 API(如 window.width)
  • 订阅第三方状态管理库
  • 订阅任何外部数据源

直接上例子:

  • 基本语法
const state = useSyncExternalStore(subscribe,  // 订阅函数getSnapshot, // 获取当前状态的函数getServerSnapshot // 可选:服务端渲染时获取状态的函数
);
  • 实战 浏览器网络状态
//useOnlineStatus hooks 
import { useSyncExternalStore } from 'react';export function useOnlineStatus() {const isOnline = useSyncExternalStore(subscribe, getSnapshot);return isOnline;
}function getSnapshot() {return navigator.onLine;
}function subscribe(callback) {window.addEventListener('online', callback);window.addEventListener('offline', callback);return () => {window.removeEventListener('online', callback);window.removeEventListener('offline', callback);};
}
  • 实战浏览器窗口宽高
// useWindowSize hooks
function useWindowSize() {const getSnapshot = () => ({width: window.innerWidth,height: window.innerHeight});const subscribe = (callback) => {window.addEventListener('resize', callback);return () => window.removeEventListener('resize', callback);};return useSyncExternalStore(subscribe, getSnapshot);
}// 组建中 hooks使用 
function NavComponent() {const { width, height } = useWindowSize();return (<div>Window size: {width} x {height}</div>);
}
  • 实战 切换主题
function createThemeStore() {let theme = 'light';const listeners = new Set();return {subscribe(listener) {listeners.add(listener);return () => listeners.delete(listener);},getSnapshot() {return theme;},toggleTheme() {theme = theme === 'light' ? 'dark' : 'light';listeners.forEach(listener => listener());}};
}const themeStore = createThemeStore();function useTheme() {return useSyncExternalStore(themeStore.subscribe,themeStore.getSnapshot);
}function ThemeToggle() {const theme = useTheme();return (<button onClick={() => themeStore.toggleTheme()}>Current theme: {theme}</button>);
}

 

注意事项

  1. 保持一致性

    • subscribe 函数应该返回清理函数
    • getSnapshot 应该返回不可变的数据
  2. 避免频繁更新

    • 考虑使用节流或防抖
    • 实现选择性订阅机制
  3. 服务端渲染

    • 提供 getServerSnapshot
    • 确保服务端和客户端状态同步
  4. 内存管理

    • 及时清理订阅
    • 避免内存泄漏

相关文章:

  • Cross Encoder 架构类型
  • UART16550 IP core笔记二
  • SpringDataRedis的入门案例,以及RedisTemplate序列化实现
  • 小皮面板从未授权到RCE
  • 【pypi镜像源】使用devpi实现python镜像源代理(缓存加速,私有仓库,版本控制)
  • 基于Python的高效批量处理Splunk Session ID并写入MySQL的解决方案
  • 【人工智能-agent】--Dify中自然语言生成SQL查询数据库
  • 如何快速入门大模型?
  • 精益数据分析(55/126):双边市场模式的挑战、策略与创业阶段关联
  • o.redisson.client.handler.CommandsQueue : Exception occured. Channel
  • 【深度学习】计算机视觉(18)——从应用到设计
  • 【大模型MCP协议】MCP官方文档(Model Context Protocol)一、开始——1. 介绍
  • Java—— 集合 Set
  • 【Spark】使用Spark集群搭建-Standalone
  • 在Web应用中集成Google AI NLP服务的完整指南:从Dialogflow配置到高并发优化
  • FFmpeg 项目中的三大核心工具详解
  • 企业管理软件:数字化转型的核心引擎
  • spdlog日志器(logger)的创建方法大全
  • 从0到1:Python机器学习实战全攻略(8/10)
  • 03.Golang 切片(slice)源码分析(二、append实现)
  • 专访|导演刘江:给谍战题材注入现实主义的魂
  • 来伊份深夜回应“粽子中吃出疑似创可贴”:拿到实物后会查明原因
  • 上海交大计算机学院成立,设多个拔尖人才特色班
  • 百利天恒董事长向复旦捐赠三千万元,用于支持创新药物靶点发现等师资建设需要
  • 中国社科院:网文市场超430亿元,作者破3000万人
  • 晶圆销量上升,中芯国际一季度营收增长近三成,净利增超1.6倍