React10 min read

React Context API: Global State Made Simple

Master React Context API for sharing state across components. Learn when to use Context vs props, and how to avoid unnecessary re-renders. Perfect for theme, user data, or any global state.

David Park
December 18, 2025
0.0k0

Passing props through many components gets annoying fast. React Context lets you share data with any component without prop drilling. Perfect for themes, user data, or any global state.

What is Context?

Context provides a way to pass data through the component tree without passing props down manually at every level. Create a context, provide a value, and consume it anywhere in your component tree.

Creating Context

It's simple - use createContext to create a context, then use Provider to wrap components that need access to it. Any component inside the Provider can access the context value.

Using Context

Use the useContext hook to access context values. It's cleaner than prop drilling and works great for data that many components need, like user info or theme settings.

Best Practices

I'll show you when to use Context vs props, how to avoid unnecessary re-renders, and how to structure your context for better performance. These patterns will make your code cleaner.

#React#Context API#State Management#Hooks

Common Questions & Answers

Q1

How do I create and use React Context?

A

Use createContext to create a context, Provider to wrap components, and useContext to access the value. Create the context, provide a value with Provider, and use useContext in any child component.

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

// Create context
const ThemeContext = createContext();

// Provider component
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Use context
function Button() {
  const { theme, setTheme } = useContext(ThemeContext);
  
  return (
    <button 
      onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
    >
      Current theme: {theme}
    </button>
  );
}

// Wrap app
function App() {
  return (
    <ThemeProvider>
      <Button />
    </ThemeProvider>
  );
}
Q2

When should I use Context vs props?

A

Use Context for data that many components need at different levels (like theme, user data, language). Use props for data that only a few nearby components need. Avoid Context for frequently changing values to prevent unnecessary re-renders.

javascript
// Good use of Context - theme used everywhere
const ThemeContext = createContext();

// Good use of props - specific to parent-child
function UserCard({ user }) {
  return <div>{user.name}</div>;
}

// Avoid Context for frequently changing data
// Instead, use state management library or lift state up