Context API is a built-in React mechanism for passing data through the entire component tree without passing through props at each level.
Simple analogy: Imagine an office building has a public address (PA) system. Before (without Context), to send a message to an employee on the 5th floor, you had to:
With Context you just speak into the microphone (Provider): "To all employees: lunch at 13:00" — and every employee (Consumer/useContext) hears it immediately, regardless of floor.
When to use:
How to use:
1// 1. Create context2const ThemeContext = React.createContext('light');34// 2. Wrap part of the tree in Provider5function App() {6 const [theme, setTheme] = useState('dark');7 return (8 <ThemeContext.Provider value={theme}>9 <Toolbar /> {/* Everything inside has access to the theme */}10 </ThemeContext.Provider>11 );12}1314// 3. Read in any nested component15function Button() {16 const theme = useContext(ThemeContext);17 return <button className={theme}>Button</button>;18}
How it works internally:
value prop changes, all consumers (components using useContext) re-render.Advanced pattern — splitting context:
1// Instead of one large context:2const AppContext = React.createContext({ user: null, theme: "light", lang: "en" });34// Split into separate contexts:5const UserContext = React.createContext(null);6const ThemeContext = React.createContext("light");7const LangContext = React.createContext("en");89// Now updating theme does NOT re-render components that only use user10function UserAvatar() {11 const user = useContext(UserContext); // Only subscribes to user changes12 return <img src={user.avatar} />;13}
Performance considerations:
Important: Context is NOT suitable for frequent updates (for example, every second). Every time value changes, all components using this Context re-render. For frequent updates, use Redux, Zustand, or other libraries.