React | Trying out React Context API + Custom Hooks for Global State

I've been using React’s Context API to simplify how I manage and share state across components—mainly to avoid prop drilling and keep things cleaner. Thought I’d share how I’ve set it up and what’s been working well for me.

✅ Local context setup (just for the navbar)

I wanted to show a logged-in user in the navbar and also have a logout button. Instead of passing user state through loads of components, I used createContext() and a custom hook.

Here’s the basic setup:

export const NavbarContext = createContext();

// custom hook for convenience
export const useAppContext = () => useContext(NavbarContext);

const Navbar = () => {
  const [user, setUser] = useState({ name: 'val' });

  const logout = () => {
    setUser(null);
  };

  return (
    <NavbarContext.Provider value={{ user, logout }}>
      <nav className='navbar'>
        <h5>CONTEXT API</h5>
        <NavLinks />
      </nav>
    </NavbarContext.Provider>
  );
};

export default Navbar;

I really like using that custom hook (useAppContext) instead of calling useContext(NavbarContext) everywhere. Just feels neater.

✅ Global context (wrapped around the whole app)

I also tried using context at the app level to store global stuff—like a user name in this case. Same idea, but this one wraps everything in the root:

import { createContext, useState, useContext } from "react";

const GlobalContext = createContext();

// custom hook again
export const useGlobalContext = () => useContext(GlobalContext);

const AppContext = ({ children }) => {
  const [name, setName] = useState("val in app");

  return (
    <GlobalContext.Provider value={{ name, setName }}>
      {children}
    </GlobalContext.Provider>
  );
};

export default AppContext;

And then in main.jsx:

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.jsx';
import AppContext from './context.jsx';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <AppContext>
      <App />
    </AppContext>
  </StrictMode>
);

That’s pretty much it. It’s simple, but honestly, Context + custom hook is already making things feel way more manageable—especially for user state, theme toggles, and other shared bits of state.

🚀 Hope this makes things a bit clearer for someone else on the same journey.

0
Subscribe to my newsletter

Read articles from Valencia Miyeon Jang directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Valencia Miyeon Jang
Valencia Miyeon Jang

Front-end developer with a background in Korean language QA and education.Experienced in localisation testing, cross-functional teamwork, and user-focused development.I enjoy crafting intuitive web experiences with React, Next.js, and TypeScript — always learning, always building.