A Context provider shares data with many components without passing props down step-by-step. It helps keep your app organized and easy to update.
0
0
Context provider in React
Introduction
You want to share a theme (like colors or fonts) across many parts of your app.
You need to share user login info with different pages or components.
You want to manage language settings for your app in one place.
You have data that many components need, and passing props would be too long or messy.
Syntax
React
const MyContext = React.createContext(defaultValue); function App() { const value = { /* data to share */ }; return ( <MyContext.Provider value={value}> {/* components that use the context */} </MyContext.Provider> ); }
The value prop is what you share with all components inside the provider.
Components inside can access this value using useContext(MyContext).
Examples
This example shares a theme value "dark" with all components inside
ThemeContext.Provider.React
const ThemeContext = React.createContext('light'); function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }
This shares user info so any child component can know who is logged in.
React
const UserContext = React.createContext(null); function App() { const user = { name: 'Anna', loggedIn: true }; return ( <UserContext.Provider value={user}> <Profile /> </UserContext.Provider> ); }
Sample Program
This app shares the language "Spanish" using a Context provider. The DisplayLanguage component reads it and shows it on screen.
React
import React, { useContext } from 'react'; const LanguageContext = React.createContext('English'); function DisplayLanguage() { const language = useContext(LanguageContext); return <p>The current language is: {language}</p>; } export default function App() { return ( <LanguageContext.Provider value="Spanish"> <DisplayLanguage /> </LanguageContext.Provider> ); }
OutputSuccess
Important Notes
Always wrap components that need the shared data inside the provider.
Changing the value in the provider updates all components using that context automatically.
Summary
Context provider shares data easily across many components.
Use React.createContext to make a context and .Provider to share data.
Access shared data inside components with useContext.