reactjs
/

React Context API – Managing Global State & Prop Drilling

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Context API – Managing Global State & Prop Drilling

What is the Context API?

The Context API is a built-in React feature that allows you to share data (state, functions, or objects) across the entire component tree without having to pass props down manually through every level. This solves the common problem known as 'prop drilling'.

The Three Pillars of Context

  • createContext: Defines the 'shape' of the data and provides a default value.
  • Provider: A component that wraps a section of your app and 'broadcasts' the data to all its descendants.
  • useContext: A hook used by any child component to 'tune in' and consume the data.

Basic Implementation

React JSXRead-only
1
import { createContext, useContext, useState } from 'react';

// 1. Create the Context
const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('dark');

  return (
    // 2. Provide the value
    <ThemeContext.Provider value={theme}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  // No props passed here!
  return <ThemedButton />;
}

function ThemedButton() {
  // 3. Consume the value
  const theme = useContext(ThemeContext);
  return <button className={theme}>I am {theme} mode</button>;
}

When to Use Context

Context is best suited for data that is considered 'global' or 'broadcast' to many components. Overusing it for localized state can make components harder to reuse.

Recommended UseAvoid If...
Theming (Light/Dark mode)The data is only used by two adjacent components
User Authentication / PermissionsThe data changes multiple times per second (performance)
Localization (Language settings)You want to keep a component highly generic/reusable
Preferred UI SettingsA simple prop-pass suffices

Performance & Memoization

Every time the value prop of a Provider changes, all components calling useContext for that specific context will re-render. To prevent unnecessary renders, always memoize the provider value if it's an object.

React JSXRead-only
1
const value = useMemo(() => ({ user, login, logout }), [user]);

return (
  <AuthContext.Provider value={value}>
    {children}
  </AuthContext.Provider>
);

Try it yourself

import React, { createContext, useContext, useState } from 'react';

// Create Context
const UserContext = createContext();

// A Nested Child
const UserProfile = () => {
  const { user, logout } = useContext(UserContext);
  return (
    <div style={{ border: '1px solid #ccc', padding: '10px' }}>
      <p>Welcome, <strong>{user.name}</strong>!</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
};

// Main App Component
export default function App() {
  const [user, setUser] = useState(null);

  const login = () => setUser({ name: 'Kishore Kumar' });
  const logout = () => setUser(null);

  return (
    <UserContext.Provider value={{ user, logout }}>
      <div style={{ padding: '20px' }}>
        <h3>Context API Auth Demo</h3>
        {user ? (
          <UserProfile />
        ) : (
          <button onClick={login}>Login as Kishore</button>
        )}
      </div>
    </UserContext.Provider>
  );
}

Test Your Knowledge

Q1
of 3

Which hook is used to consume a context value?

A
useProvider
B
useContext
C
useReducer
D
useState
Q2
of 3

What is 'prop drilling'?

A
Optimizing props for faster rendering
B
Passing props through components that don't need them
C
A method to delete unused props
D
The process of validating prop types
Q3
of 3

Where should the Provider typically be placed?

A
Inside the component that needs the data
B
In a separate CSS file
C
High up in the component tree (like App.js)
D
Inside the node_modules folder

Frequently Asked Questions

Is Context API a replacement for Redux?

Not exactly. Context is a dependency injection tool for avoiding prop drilling. Redux/Zustand are state management libraries with devtools, middleware, and optimized selection logic.

Can I have multiple Providers?

Yes! It is a best practice to split contexts (e.g., ThemeProvider, AuthProvider) rather than having one giant global context object.

What is the default value in createContext for?

The default value is only used if a component tries to consume a context but is NOT wrapped inside a matching Provider.

Previous

react uncontrolled components

Next

react redux intro

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.