Home About Skills Products
Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

useContext and the Context API - Ending Prop Drilling

useContext and the Context API - Ending Prop Drilling

When data (like a logged-in user, theme, or language) needs to pass down 4-5 levels through the component tree, doing it with props alone turns into "prop drilling" — every component in between just forwards those props without ever using them itself. The Context API solves this.

Step 1: Create a Context

// ThemeContext.js
import { createContext } from 'react';

export const ThemeContext = createContext('light');

Step 2: Supply a Value with a Provider

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

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Dashboard />
    </ThemeContext.Provider>
  );
}

Step 3: Consume It in Any Nested Component

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

function ThemeToggleButton() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Current theme: {theme}
    </button>
  );
}

No matter how deeply nested ThemeToggleButton is inside Dashboard, it can directly access theme and setTheme without any props being passed down.

When to Use Context (and When Not To)

  • ✅ For global-ish data: the auth user, theme, language, cart.
  • ❌ Don't create a context for every small piece of state — plain props are fine when data only travels 1-2 levels.
  • ⚠️ When a context value changes, every consumer re-renders — for very frequently-changing data (like mouse position), context isn't the right choice.

Key Takeaways

  • The Context API is a clean solution to prop drilling.
  • 3 steps: createContext<Provider value> → read with useContext.
  • For very frequently changing values, a dedicated state library may scale better than Context.
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Advertisement
Esc