【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)
  • 适合中小项目
相关推荐
m0_738120722 小时前
CTFshow系列——命令执行web38-40
前端·windows·安全·web安全
zhoxier3 小时前
elementui el-select 获取value和label 以及 对象的方法
javascript·vue.js·elementui
是小狐狸呀3 小时前
elementUI-表单-下拉框数据选中后,视图不更新
前端·javascript·elementui
四岁半儿6 小时前
常用css
前端·css
你的人类朋友6 小时前
说说git的变基
前端·git·后端
姑苏洛言6 小时前
网页作品惊艳亮相!这个浪浪山小妖怪网站太治愈了!
前端
字节逆旅6 小时前
nvm 安装pnpm的异常解决
前端·npm
Jerry7 小时前
Compose 从 View 系统迁移
前端
IT码农-爱吃辣条7 小时前
Three.js 初级教程大全
开发语言·javascript·three.js
GIS之路7 小时前
2025年 两院院士 增选有效候选人名单公布
前端