Context API
Definition
The Context API provides a way to pass data through the component tree without having to pass props down manually at every level (avoiding 'prop drilling').
Explain Like I'm New
Imagine a 5-story office building. The CEO on the top floor wants to give a memo to a worker on the 1st floor. Normally, the CEO hands it to the VP on floor 4, who hands it to a Manager on floor 3, who hands it to a Supervisor on floor 2, who finally gives it to the worker (Prop Drilling). Context is like a PA system. The CEO speaks into the microphone, and anyone in the building who cares can just listen to the speaker on their floor, skipping all the middlemen.
Real World Example
Managing Dark Mode/Light Mode. Almost every component in your app needs to know what theme is active to style itself correctly. Passing `theme="dark"` through 50 layers of components is miserable. Context makes it globally available.
Common Use Cases
- •Theming (Dark/Light mode)
- •Current authenticated user data
- •Language/Localization settings
Interactive Example
import React, { createContext, useContext, useState } from 'react'; // 1. Create the Context const ThemeContext = createContext('light'); export default function App() { const [theme, setTheme] = useState('light'); return ( // 2. Provide the Context to all children <ThemeContext.Provider value={theme}> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}> Toggle Theme </button> <MiddlemanComponent /> </ThemeContext.Provider> ); } // Notice this component doesn't take any props! function MiddlemanComponent() { return ( <div> <h2>I am the middleman. I don't care about the theme.</h2> <DeepChildComponent /> </div> ); } function DeepChildComponent() { // 3. Consume the Context directly where it's needed const theme = useContext(ThemeContext); return ( <div style={{ padding: '20px', background: theme === 'dark' ? '#333' : '#FFF', color: theme === 'dark' ? '#FFF' : '#000' }}> Current Theme is: {theme} </div> ); }
Interview Questions
basic
- What is 'Prop Drilling'?
- How do you consume a Context in a functional component?
intermediate
- What are the three main steps to using Context?
- What is the `<Context.Provider>` used for?
advanced
- Why can the Context API cause performance issues in large apps?
- How can you prevent unnecessary re-renders when a Context value changes?
trick
- Can a component consume multiple different Contexts at the same time?