Discover how to share data effortlessly across your whole React app without endless prop passing!
Why Context provider in React? - Purpose & Use Cases
Imagine you have a React app with many components nested inside each other. You want to share user settings like theme or language across all these components. Without a context provider, you have to pass these settings down through every component manually as props.
Passing props through many layers is tiring and error-prone. If you forget to pass a prop at any level, the components below won't get the data. It also makes your code messy and hard to maintain.
Context provider lets you share data globally in your app without passing props manually. Components can access the shared data directly from the context, no matter how deep they are nested.
function App() {
return <Parent user={user} />;
}
function Parent({ user }) {
return <Child user={user} />;
}
function Child({ user }) {
return <div>{user.name}</div>;
}const UserContext = React.createContext();
function App() {
return <UserContext.Provider value={user}>
<Child />
</UserContext.Provider>;
}
function Child() {
const user = React.useContext(UserContext);
return <div>{user.name}</div>;
}It enables easy and clean sharing of data across many components without messy prop passing.
Think of a website where the user's chosen theme (dark or light) applies everywhere instantly, no matter which page or component they visit.
Passing props through many layers is hard and error-prone.
Context provider shares data globally in React apps.
It makes your code cleaner and easier to maintain.