react不用redux如何定义全局变量
使用Context API
React的Context API是官方推荐的全局状态管理方案。创建一个Context对象,通过Provider传递数据,子组件通过useContext或Consumer获取数据。适合中小型应用的状态共享需求。
import React, { createContext, useContext } from 'react';
const GlobalContext = createContext();
export const GlobalProvider = ({ children }) => {
const [count, setCount] = React.useState(0);
return (
<GlobalContext.Provider value={{ count, setCount }}>
{children}
</GlobalContext.Provider>
);
};
export const useGlobal = () => useContext(GlobalContext);
自定义Hook结合useState
将状态和逻辑封装到自定义Hook中,通过模块化导出实现全局共享。适用于逻辑复用但不需要跨组件层级传递的场景。

import { useState } from 'react';
const useGlobalStore = () => {
const [user, setUser] = useState(null);
return { user, setUser };
};
export default useGlobalStore;
模块化全局对象
直接通过JavaScript模块特性定义全局变量。模块在首次导入时初始化,所有导入共享同一实例。注意避免直接修改对象导致不可预测的副作用。

// globalStore.js
export default {
theme: 'light',
setTheme(theme) {
this.theme = theme;
}
};
// 组件中使用
import globalStore from './globalStore';
console.log(globalStore.theme);
使用useReducer与Context结合
对于复杂状态逻辑,useReducer可替代useState,结合Context实现类Redux的功能。通过dispatch统一管理状态变更。
const initialState = { todos: [] };
function reducer(state, action) {
switch (action.type) {
case 'ADD_TODO':
return { ...state, todos: [...state.todos, action.payload] };
default:
return state;
}
}
const StoreContext = createContext();
export const StoreProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={{ state, dispatch }}>
{children}
</StoreContext.Provider>
);
};
第三方轻量库
若需更结构化方案但不愿使用Redux,可考虑Zustand、Jotai或Recoil等轻量库。例如Zustand通过简洁的API实现状态管理:
import create from 'zustand';
const useStore = create(set => ({
bears: 0,
increase: () => set(state => ({ bears: state.bears + 1 })),
}));
// 组件中使用
function Counter() {
const { bears, increase } = useStore();
return <button onClick={increase}>{bears}</button>;
}






