Context API
Context provides a way to pass data through the component tree without manually passing props at every level.
Mental Model
"The Radio Broadcast: The radio tower broadcasts music to the entire city; any house with a radio receiver tunes in directly."
Interactive Engine Walkthrough
Reference Code Snippet
1const ThemeContext = createContext("dark");
2
3function App() {
4 return (
5 <ThemeContext.Provider value="light">
6 <DeepChild />
7 </ThemeContext.Provider>
8 );
9}
10
11function DeepChild() {
12 const theme = useContext(ThemeContext);
13 return <div>{theme}</div>;
14}- 01.Avoids "prop drilling" where intermediary components pass props they never consume.
- 02.Every component calling useContext(MyContext) re-renders whenever the context value changes.
- 03.Split large contexts into smaller, focused contexts (e.g. AuthContext, ThemeContext) to limit re-renders.
01. Tree Broadcasting
Context allows a parent component to provide data to its entire subtree without passing it through every intermediate child. This is ideal for global data like **Theming**, **User Auth**, or **Language preferences**.
Data Transmission
02. Performance Warning
Context is **not** a state management tool like Redux. When the value in a Provider changes, **every single component** that uses `useContext` for that provider will re-render. Frequent updates to a giant context object can lead to noticeable lag.
Senior Architect Tip
"Separate your contexts. Don't put 'user', 'settings', and 'theme' in one giant context. Create small, atomic providers to ensure only the necessary parts of the tree re-render when a specific value changes."