Context API: Avoiding Prop Drilling

Context API: Avoiding Prop Drilling in JavaScript: Imagine you are in a 50-story building. You want to give a letter to someone on the 50th floor.

Concept Explanation

Imagine you are in a 50-story building. You want to give a letter to someone on the 50th floor. If you have to hand it to the person on the 1st floor, who gives it to the 2nd, and so on... that's Prop Drilling. It's exhausting.

The Context API is like a "Pneumatic Tube" system. You put the letter in the tube on the 1st floor, and it pops out exactly where it's needed on the 50th floor, skipping everyone in between.


Syntax or Core Structure (React Example)

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

// 2. Provide the data at the top
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// 3. Consume the data at the bottom
function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>I am {theme} themed!</button>;
}

Real World Example

User Authentication: You wrap your whole app in an AuthContext. Now, any component (The Navbar, the Settings page, the "Buy" button) can immediately check isLoggedIn without having to pass that data through every single layout component.


Practice Exercises

  1. The Language Switcher: Create a mock Context that stores a "Language" (en, es, fr).
  2. The Consumer: Write a component that reads from the Language Context and displays a greeting.
  3. The Multi-Context: Research "Context Composition" and explain why you shouldn't put everything into one giant Context object.