React
Context API
Context API is a built-in React mechanism for passing data through a component tree without having to pass props manually. It solves the prop drilling problem, making common values (theme, language, authorization) available at any level of the hierarchy.
What is Context
- Context creates a global store for the React tree.
- It consists of three elements:
React.createContext(defaultValue)— creates a context object.<Context.Provider>— provides a value for all descendants.useContext(Context)— allows child components to get the current value.
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <Button theme={theme} />;
}How Context Works
- All components located inside a Provider subscribe to changes in the context value.
- When
valueis updated, React re-renders only the subscribed components. - Components outside a Provider use
defaultValue.
Typical Use Cases
- Theming (Theme switching)
<ThemeContext.Provider value="dark">...</ThemeContext.Provider>- User Authorization (AuthContext)
<AuthContext.Provider value={user}>...</AuthContext.Provider>- Localization Settings (LanguageContext)
<LanguageContext.Provider value="en">...</LanguageContext.Provider>Limitations and Best Practices
- Frequent context updates can cause redundant re-renders.
- It is better to split contexts by responsibility zones (theme, language, data).
- For complex state, it is better to use Redux or Zustand.
- Do not use Context for temporary or frequently changing data.
Key ideas
- Context API eliminates the need for prop drilling.
Providerdefines the data source,useContext— the consumer.- Works at the React tree level, not the global state level of the application.
- Effective for global, rarely changing settings (theme, language, session).