advanced#react#context api#state management
Advanced State Management with React Context API
Learn how to use the React Context API to manage state in complex applications, including creating a context, providing a context, and consuming a context.
Introduction to React Context API
In this tutorial, we will learn how to use the React Context API to manage state in complex applications. We will cover creating a context, providing a context, and consuming a context.
Step 1: Creating a Context
First, we need to create a new context. We can do this by creating a new file called ThemeContext.js in the src directory:
import React, { createContext, useState } from 'react';
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
export { ThemeContext, ThemeProvider };
Step 2: Providing a Context
Next, we need to provide our context to our application. We can do this by wrapping our App component with our ThemeProvider component:
import React from 'react';
import { ThemeProvider } from './ThemeContext';
import App from './App';
const Root = () => {
return (
<ThemeProvider>
<App />
</ThemeProvider>
);
};
export default Root;
Step 3: Consuming a Context
Finally, we can consume our context in our components. We can do this by using the useContext hook:
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Button() {
const { theme } = useContext(ThemeContext);
return (
<button style={{ backgroundColor: theme === 'light' ? '#fff' : '#333' }}>
Click me
</button>
);
}
export default Button;