The Context API in React lets you share data globally across components β without passing props manually at every level.
π― Why use Context?
β’ Avoids prop drilling (passing props through many levels)
β’ Great for global data like theme, auth, or language
β’ Makes state management cleaner in medium apps
π§± Basic setup:
1.Create a context:
import { createContext } from "react";
export const ThemeContext = createContext();
2.Provide context in a parent:
function App() {
return (
<ThemeContext.Provider value={"dark"}>
<Child />
</ThemeContext.Provider>
);
}
3.Use context in any child:
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function Child() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
π Key points:
β’ Use createContext to create a new context
β’ Use Provider to wrap the tree and pass a value
β’ Use useContext to access the value anywhere
Context API is perfect for lightweight global state without external libraries like Redux.
Top comments (0)