React's Context API

React's Context API

Kusal K C

The Problem: Prop Drilling

Imagine you're building a website with a theme switcher (dark/light mode). Your app structure might look like this:

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

  return (
    <div>
      <Header theme={theme} />

      <MainContent theme={theme}>
        <Sidebar theme={theme}>
          <UserProfile theme={theme} />
        </Sidebar>
      </MainContent>
    </div>
  );
React App showing Prop Drilling

Notice how we're passing the theme prop through every component, even if some components (like MainContent) don't actually use it - they just pass it down to their children. This is called "prop drilling" and it creates several problems:

  • Makes code harder to maintain
  • Creates unnecessary coupling between components
  • Makes components less reusable
  • Gets messy with deeply nested components


The Solution: Context API

React's Context API allows you to create a "shared state" that any component in your app can access without explicitly having to pass down through components as props. Here's how to use it:

  1. First, create a context:
// ThemeContext.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');

2. Wrap your app (or the part that needs the shared state) with a Provider:

// App.js
import { ThemeContext } from './ThemeContext';

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

    <MainContent>
     <Sidebar>
      <UserProfile />
     </Sidebar>
    </MainContent>
   </div>
  </ThemeContext.Provider>
 );
}


3. Use the context in any component that needs it:

// UserProfile.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function UserProfile() {
 const theme = useContext(ThemeContext);

 return (
  <div className={`profile ${theme}`}>
   {/* Component content */}
  </div>
 );
}

Using Context API allows us to use the state from provider by referencing the Context with useContext hook.


Looking at the diagram above:

  • In the "Prop Drilling" example, each component must manually pass down the theme prop
  • In the "Context API" example, components can directly access the theme value from the Context Provider (shown by the dotted lines)


When to Use Context API

Context is great for:

  • Theme data (dark/light mode)
  • User authentication state
  • Language preferences
  • Any data that needs to be accessible by many components at different nesting levels

However, don't use Context for everything! It's not a replacement for component props when:

  • The data is only needed by immediate children
  • The data changes very frequently (might cause unnecessary re-renders)
  • You only need to pass data through one or two levels


Report Page