当前位置: 首页 > 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. 内存管理

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

http://www.xdnf.cn/news/409231.html

相关文章:

  • 面向对象的js
  • 短视频兴趣算法的实现原理与技术架构
  • Linux512 ssh免密登录 ssh配置回顾
  • 写项目遇到的通用问题
  • Windows 安装 Milvus
  • 论坛项目测试
  • Matlab 模糊pid控制的永磁同步电机PMSM
  • 前端面经 计网 http和https区别
  • ​Spring Boot 配置文件敏感信息加密:Jasypt 实战
  • 国产密码新时代!华测国密 SSL 证书解锁安全新高度
  • 开疆智能canopen转Profinet网关连接AGV磁钉读头配置案例
  • HTTP2
  • Java中实现定时器的常见方式
  • C 语 言 - - - 简 易 通 讯 录
  • 网页Web端无人机直播RTSP视频流,无需服务器转码,延迟300毫秒
  • 致远OA人事标准模块功能简介【附应用包百度网盘下载地址,官方售价4W】
  • OpenCV直方图与直方图均衡化
  • Unity动画系统使用整理 --- Playable
  • python标准库--collections - 高性能数据结构在算法比赛的应用
  • LVGL(线条控件lv_line)
  • CentOS 和 RHEL
  • FPGA----基于ZYNQ 7020实现定制化的EPICS程序开发
  • AI Agent开发第64课-DIFY和企业现有系统结合实现高可配置的智能零售AI Agent
  • 智能外呼系统的实用性
  • LGDRL:基于大型语言模型的深度强化学习在自动驾驶决策中的应用
  • bea算法,大模型
  • Linux文件系统
  • C++11新特性(1)
  • Aware和InitializingBean接口以及@Autowired注解失效分析
  • 内存泄漏系列专题分析之十一:高通相机CamX ION/dmabuf内存管理机制Camx ImageBuffer原理