Back to React Hooks
3

useContext

Share data without prop drilling

Intermediate

Core Concepts

  • Context lets components share data without passing props manually
  • createContext creates a context object
  • Context.Provider wraps components that need access
  • useContext reads the current value from the nearest Provider
  • Avoids "prop drilling" — passing props through many levels

Live Demo

The button is nested 2 levels deep, but accesses theme directly via context:

🧩Parent Component

Provides context

🧩Toolbar component

No props passed!

Without vs With Context

Prop Drilling

<Parent theme={theme}>
  <Toolbar theme={theme}>
    <Button theme={theme} />
  </Toolbar>
</Parent>

With Context

<ThemeContext.Provider>
  <Toolbar>
    <Button /> // reads context
  </Toolbar>
</ThemeContext.Provider>

Code


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

// 1. Create context with default value
const ThemeContext = createContext('light');

// 2. Child component consumes context
function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Click me</button>;
}

// 3. Parent provides context value
function App() {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={theme}>
      <ThemedButton />
    </ThemeContext.Provider>
  );
}
                  

When to Use Context vs Redux?

Use Context for

  • Theme, locale, auth user
  • Data that changes infrequently
  • Simple state sharing

Use Redux for

  • Complex state logic
  • Frequent updates
  • DevTools, middleware, persistence