Topic 41 of 54
createContext
Overview
React Context provides a way to 'teleport' data through the component tree without having to pass props down manually at every level. It's built directly into React. You create a Context, wrap a section of your app in a Context 'Provider', and give it a value. Any component inside that Provider (no matter how deep) can instantly tap into that value.
Syntax
The `createContext` function returns an object containing a `Provider` and a `Consumer`. We wrap our component tree in the `<Provider>` and pass it the data we want to share globally via the `value` prop.
Creating and Providing Context
jsx
import { createContext, useState } from 'react';
// 1. Create the Context (usually in its own file)
// We export it so other files can import it
export const ThemeContext = createContext("light"); // "light" is a fallback default
// 2. Wrap your app (or part of it) in the Provider
function App() {
const [theme, setTheme] = useState("dark"); // This is the real state
return (
// The Provider broadcasts the 'value' to everything inside it
<ThemeContext.Provider value={theme}>
<Layout />
</ThemeContext.Provider>
);
}Common Pitfalls
- Putting an object literal directly in the Provider's `value` prop (e.g., `value={{ color: 'red' }}`). This creates a *brand new object reference* on every render of the parent, forcing *every single consuming component* to re-render, destroying performance. Always memoize complex values!
Interview Tips
- Understand that Context is NOT a state manager. It is a state *transport* mechanism. You still need `useState` or `useReducer` to actually manage the state; Context just moves it around.
Real-World Example
A Context Provider is often wrapped in its own Custom Component to keep the `App.jsx` file clean.
example
jsx
// AuthProvider.jsx
export const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
// We can bundle functions with the state!
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
// App.jsx
function App() {
return (
<AuthProvider>
<Router />
</AuthProvider>
);
}