Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Context in React is a way to pass data between components at any nesting level, bypassing manual prop passing (props) through each tree level.
Context is convenient when certain data (e.g., current user, language, theme) is needed in many components simultaneously.
import { createContext } from "react";
const ThemeContext = createContext("light");
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
import { useContext } from "react";
function Header() {
const theme = useContext(ThemeContext);
return <h1 className={`header ${theme}`}>Hello!</h1>;
}
Now Header component knows theme is "dark", without props!
const value = useContext(ContextObject);
Context.ProviderProvider changesconst ThemeContext = createContext("light");
function ThemeSwitcher() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Switch theme</button>;
}
useContext hook allows easy access to context value.Tip:
Use context for data that's needed by many components and rarely changes.