Context API
The Context API lets you share global state across your entire app without 'prop drilling'.
Learning Goals
The Core Concept
Normally, data is passed top-down from parent to child via props. However, if you have deeply nested components, passing props through every intermediate component (known as 'prop drilling') becomes tedious and messy. The Context API acts like a global broadcast system. You create a Context Provider at the top of your app, and any component anywhere in the tree can 'consume' that context directly to access the data or functions it needs.
Visual guide
React concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
import { createContext, useContext, useState } from 'react';
// 1. Create the Context
const ThemeContext = createContext();
function ThemedText() {
// 3. Consume the Context
const { theme } = useContext(ThemeContext);
return <p>The current theme is {theme}.</p>;
}
export default function App() {
const [theme, setTheme] = useState('light');
return (
// 2. Provide the Context
<ThemeContext.Provider value={{ theme, setTheme }}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
<ThemedText />
</ThemeContext.Provider>
);
}Expected Output
[Toggle Theme] The current theme is light.
Job Portal Frontend
Hands-on practice task
The Challenge
Build a job portal layout using Context to manage the currently logged-in user. Any component should be able to greet the user or show a login button.
Helpful Hints
- •Create an `AuthContext` holding a `user` object and `login`/`logout` functions.
- •Create a Navbar that consumes the context to show 'Welcome, [Name]' or 'Login'.
- •Create a Main Content area that also consumes the context to either show job listings or prompt the user to log in.
Quick Knowledge Check
Is Context a replacement for Redux?
Continue Learning
Next steps after this lesson
Build a job portal layout using Context to manage the currently logged-in user. Any component should be able to greet the user or show a login button.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.