The Context API in React is a powerful feature that allows you to share state across the entire component tree without the need to pass props manually at each level. It provides a way to create global data (such as user authentication status, theme settings, or language preferences) that can be accessed by any component in the tree, no matter how deep.
Key Concepts
- React.createContext(): This function creates a Context object. This object will hold the data you want to share across components.
const MyContext = React.createContext();
- Context.Provider: The
Provider
component is used to pass the context value to all its descendants. It accepts avalue
prop, which will be available to any component in the tree that consumes the context.<MyContext.Provider value={someValue}> <ChildComponent /> </MyContext.Provider>
- Context.Consumer: The
Consumer
component allows any descendant component to access the context value. It uses a function as a child to receive the context value.<MyContext.Consumer> {value => <div>{value}</div>} </MyContext.Consumer>
- useContext Hook (for function components): Instead of using the
Consumer
component, theuseContext
hook allows you to directly access the context value in functional components.const value = useContext(MyContext);
Example Usage:
Here’s a simple example demonstrating how to use the Context API to manage a theme (light or dark) globally:
import React, { createContext, useState, useContext } from 'react';
// Create a Context object
const ThemeContext = createContext();
// Provider component
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
// Component that consumes the context
const ThemedComponent = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
<h1>The current theme is {theme}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
// App component
const App = () => (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
export default App;
Explanation:
ThemeContext
is created usingcreateContext()
.ThemeProvider
wraps the component tree with a context provider, passing the currenttheme
andtoggleTheme
function as the context value.ThemedComponent
uses theuseContext
hook to access the theme and toggle the theme.
When to Use Context API:
- When you need to share state between deeply nested components without having to pass props through every level.
- For global states like user authentication, theme, or language preferences.
- In complex applications with many components that need to access the same data.