Context
In React, the Context API provides a way to share data between components without having to pass props down manually at every level. It's particularly useful for sharing global data like authentication status, theme settings, or user information across various parts of an application.
How It Works
Create a Context: First, you create a new context using
React.createContext()
. This returns a Context object with aProvider
and aConsumer
.const MyContext = React.createContext();
Provide a Context Value: Use the
Provider
component at the top level of your component tree to provide a value that will be accessible to all child components.<MyContext.Provider value={{ someValue: 'hello' }}>
{/* children */}
</MyContext.Provider>Consume the Context: Any child component can access the context value without it being explicitly passed in as a prop. You can use the
Consumer
component or theuseContext
hook to consume the context.// Using Consumer
<MyContext.Consumer>
{(context) => /* render something based on context */}
</MyContext.Consumer>
// Using useContext hook
const context = useContext(MyContext);
Example
Here's a simple example to demonstrate how context works:
import React, { useContext, useState } from 'react';
// Create Context
const ThemeContext = React.createContext();
// Parent Component
const App = () => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
};
// Child Component
const Toolbar = () => {
return (
<div>
<ThemedButton />
</div>
);
};
// Grandchild Component
const ThemedButton = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
style={{
backgroundColor: theme === 'light' ? '#fff' : '#000',
color: theme === 'light' ? '#000' : '#fff',
}}
>
Toggle Theme
</button>
);
};
In this example, the ThemedButton
component can access the theme
and setTheme
without them being passed down as props, thanks to the Context API.
When to Use Context
Context is mainly used when some data needs to be accessible by many components at different nesting levels. However, it's not recommended to use context for every state in your application. Use it sparingly and only for state that is truly global.