useContext Hook
-
This lesson introduces the useContext Hook and explains how to manage and share global data across React components.
Topic Overview
Advanced React Hooks help manage global state, complex logic, DOM access, and performance optimization.
These hooks are essential for real-world React applications.useContext Hook
Context API Overview
The Context API is used to share data globally across components without passing props manually.
Solves the problem of prop drilling.
Examples of global data:
Theme (dark/light)
User authentication
Language settings
Creating Context
Context is created using createContext().
Example:
import { createContext } from "react";
const ThemeContext = createContext();
This creates a global data container.
Providing and Consuming Context
Providing Context:
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
Consuming Context:
import { useContext } from "react";
const theme = useContext(ThemeContext);
Any component can access the value directly.