Context provides a way to pass data through the component tree without having to pass props down manually at every level. It’s especially useful for global state management, such as user authentication, themes, or language settings.
useContextThe useContext hook allows you to consume a context directly inside a functional component, bypassing the need to use a Context.Consumer wrapper. Here’s a step-by-step guide on how to use useContext.
First, create a context using React.createContext(). This context will hold the data you want to share across your components.
import { createContext } from 'react';
// Create a context with a default value (optional)
const ThemeContext = createContext('light');
export default ThemeContext;
To make the context available to your components, wrap your component tree with the Provider component from the context you created. The value prop of the Provider is where you pass the data that needs to be shared.
// App.js
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
import ThemedComponent from './ThemedComponent';
function App() {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={theme}>
<button onClick={toggleTheme}>Toggle Theme</button>
<ThemedComponent />
</ThemeContext.Provider>
);
}
export default App;
useContextNow, you can use useContext to access the context value inside your functional components.
// ThemedComponent.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
function ThemedComponent() {
const theme = useContext(ThemeContext);
const styles = {
backgroundColor: theme === 'light' ? '#fff' : '#333',
color: theme === 'light' ? '#000' : '#fff',
padding: '20px',
textAlign: 'center',
};
return <div style={styles}>The current theme is {theme}</div>;
}
export default ThemedComponent;