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. 内存管理

    • 及时清理订阅
    • 避免内存泄漏
相关推荐
2501_9209317039 分钟前
React Native鸿蒙跨平台实现推箱子游戏,完成玩家移动与箱子推动,当所有箱子都被推到目标位置时,玩家获胜
javascript·react native·react.js·游戏·ecmascript·harmonyos
layman05281 小时前
webpack5 css-loader:从基础到原理
前端·css·webpack
半桔1 小时前
【前端小站】CSS 样式美学:从基础语法到界面精筑的实战宝典
前端·css·html
AI老李1 小时前
PostCSS完全指南:功能/配置/插件/SourceMap/AST/插件开发/自定义语法
前端·javascript·postcss
_OP_CHEN1 小时前
【前端开发之CSS】(一)初识 CSS:网页化妆术的终极指南,新手也能轻松拿捏页面美化!
前端·css·html·网页开发·样式表·界面美化
啊哈一半醒1 小时前
CSS 主流布局
前端·css·css布局·标准流 浮动 定位·flex grid 响应式布局
PHP武器库1 小时前
ULUI:不止于按钮和菜单,一个专注于“业务组件”的纯 CSS 框架
前端·css
方也_arkling1 小时前
Element Plus主题色定制
javascript·sass
电商API_180079052471 小时前
第三方淘宝商品详情 API 全维度调用指南:从技术对接到生产落地
java·大数据·前端·数据库·人工智能·网络爬虫
晓晓莺歌1 小时前
vue3某一个路由切换,导致所有路由页面均变成空白页
前端·vue.js