The " Courier Delivery " Problem (Prop Drilling)

Imagine your application is a huge skyscraper.

  • On the roof (App) lies a package (user data).
  • It's needed by a person in the basement (Avatar).
  • You have to force every resident on every floor to take this package and pass it further. Meanwhile, residents on the 50th floor don't care what's inside this package. In programming, this is called Prop Drilling, and it makes code fragile and dirty.

1. Analogy: Radio Station

Context API turns " courier delivery " into " radio broadcasting " .

  • Provider (Radio Tower): You put it on the roof. It broadcasts data (e.g., theme or language) on the air.
  • useContext (Receiver): Any component on any " floor " can simply take out their receiver, tune to the right frequency, and get data instantly. They don't need to ask parents to pass something.

2. Three Steps to Setting Up the Broadcast

  1. Create a frequency:
    const ThemeContext = createContext('light'); // 'light' - fallback value
    
  2. Turn on broadcasting (Provider): Wrap the needed part of the application. Everything inside Provider has access to the broadcast.
    <ThemeContext.Provider value="dark">
      <MainContent />
    </ThemeContext.Provider>
    
  3. Catch the signal (useContext):
    const theme = useContext(ThemeContext);
    

3. Critical Nuances: When Is Context Dangerous?

Many think Context is a replacement for Redux or Zustand. It's not.

  • Update problem: Context doesn't know how to update data " precisely " . If your Context contains an object with 100 fields and you change one — all components using this Context will be redrawn.
  • Advice: Use Context for " rare " data:
    • Current language (RU/EN).
    • Theme (Dark/Light).
    • Profile data (if it changes once an hour). For data that changes every second (mouse movement, timer, input in field), use local state or advanced state managers.

Context is a tool for 'Dependency Injection'. It makes your component tree clean, freeing it from unnecessary intermediary props.