How Do I Manage Global State with Hooks in React?

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.

🔗 Step-by-Step: Global State with useContext + useReducer

1️⃣ Create a Context

import { createContext } from "react";

export const AppContext = createContext();

2️⃣ Define the Reducer and Initial State

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;
  }
}

3️⃣ Create a Context Provider

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>
  );
};

4️⃣ Use the Global State in Any Component

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>
  );
}

🛠️ Best Practices for Hook-Based Global State

Tip Why It Matters
Split the state into modules Avoid bloated, monolithic state trees
Use custom hooks (useAuth) Encapsulate logic and reduce duplication
Memoize context values Prevent unnecessary re-renders
Avoid deeply nested providers Keep the structure flat and maintainable

🔥 Alternatives to Redux with Hooks

Tool Use When
useContext + useReducer Most apps with medium complexity
Zustand, Jotai, Recoil Need atomic/global state with better DX
Redux Toolkit + Hooks Complex apps or large teams

✅ Conclusion

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.