【React】使用 useContext + useReducer 实现一个轻量的状态管理库

使用 useContext + useReducer 实现的轻量级状态管理,适合中小型 React 应用使用。


🧠 实现思路

  1. 使用 createContext 创建两个上下文:StateContextDispatchContext
  2. useReducer 管理状态逻辑。
  3. 创建一个 Provider 组件包裹应用。
  4. 提供两个 hooks:useGlobalState()useGlobalDispatch(),分别获取状态和派发方法。

✅ 示例代码

1️⃣ 创建状态管理库:store.js

jsx 复制代码
import React, { createContext, useReducer, useContext } from 'react';

// 定义初始状态
const initialState = {
  count: 0,
  user: null,
};

// 定义 reducer
function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'SET_USER':
      return { ...state, user: action.payload };
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

// 创建两个上下文
const StateContext = createContext(null);
const DispatchContext = createContext(null);

// 创建 Provider
export function GlobalProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <StateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>
  );
}

// 封装 hooks
export function useGlobalState() {
  const context = useContext(StateContext);
  if (context === undefined) {
    throw new Error('useGlobalState must be used within a GlobalProvider');
  }
  return context;
}

export function useGlobalDispatch() {
  const context = useContext(DispatchContext);
  if (context === undefined) {
    throw new Error('useGlobalDispatch must be used within a GlobalProvider');
  }
  return context;
}

2️⃣ 使用示例

App.js
jsx 复制代码
import React from 'react';
import { GlobalProvider } from './store';
import Counter from './Counter';
import User from './User';

function App() {
  return (
    <GlobalProvider>
      <h1>My App</h1>
      <Counter />
      <User />
    </GlobalProvider>
  );
}

export default App;

Counter.js
jsx 复制代码
import React from 'react';
import { useGlobalState, useGlobalDispatch } from './store';

function Counter() {
  const { count } = useGlobalState();
  const dispatch = useGlobalDispatch();

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
}

export default Counter;

User.js
jsx 复制代码
import React from 'react';
import { useGlobalState, useGlobalDispatch } from './store';

function User() {
  const { user } = useGlobalState();
  const dispatch = useGlobalDispatch();

  const login = () => {
    dispatch({ type: 'SET_USER', payload: { name: 'Heo Hao' } });
  };

  return (
    <div>
      <h2>User: {user ? user.name : 'Guest'}</h2>
      <button onClick={login}>Login</button>
    </div>
  );
}

export default User;

🧩 优点

  • 不依赖第三方库(如 Redux、Zustand)
  • 轻量、易用、类型安全(可结合 TS)
  • 适合中小项目
相关推荐
翻滚吧键盘19 分钟前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js
苦夏木禾23 分钟前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉31 分钟前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
秃了也弱了。37 分钟前
Chrome谷歌浏览器插件ModHeader,修改请求头,开发神器
前端·chrome
乆夨(jiuze)1 小时前
记录H5内嵌到flutter App的一个问题,引发后面使用fastClick,引发后面input输入框单击无效问题。。。
前端·javascript·vue.js
忧郁的蛋~1 小时前
HTML表格导出为Excel文件的实现方案
前端·html·excel
小彭努力中1 小时前
141.在 Vue 3 中使用 OpenLayers Link 交互:把地图中心点 / 缩放级别 / 旋转角度实时写进 URL,并同步解析显示
前端·javascript·vue.js·交互
然我2 小时前
别再只用 base64!HTML5 的 Blob 才是二进制处理的王者,面试常考
前端·面试·html
NanLing2 小时前
【纯前端推理】纯端侧 AI 对象检测:用浏览器就能跑的深度学习模型
前端
呆呆的心2 小时前
前端必学:从盒模型到定位,一篇搞定页面布局核心 🧩
前端·css