You don’t need Redux or third-party libraries to manage global state in React. Thanks to React hooks, you can use built-in tools like,
Together, they offer a lightweight, scalable state management pattern.
import { createContext } from "react"; export const AppContext = createContext();
const initialState = { user: null, theme: "light", }; function reducer(state, action) { switch (action.type) { case "LOGIN": return { ...state, user: action.payload, }; case "TOGGLE_THEME": return { ...state, theme: state.theme === "light" ? "dark" : "light", }; default: return state; } }
import React, { useReducer } from "react"; import { AppContext } from "./AppContext"; export const AppProvider = ({ children }) => { const [state, dispatch] = useReducer(reducer, initialState); return ( <AppContext.Provider value={{ state, dispatch }}> {children} </AppContext.Provider> ); };
import { useContext } from "react"; import { AppContext } from "./AppContext"; function Profile() { const { state, dispatch } = useContext(AppContext); return ( <div> <p>User: {state.user?.name}</p> <button onClick={() => dispatch({ type: "TOGGLE_THEME" })}> Toggle Theme </button> </div> ); }
React hooks offer a clean, modern way to manage global state.
💡 Pro Tip: Wrap common logic into custom hooks like useAuth, useTheme, or useCart to stay DRY and organized.