import React from'react';
const ThemeContext = React.createContext();
export default ThemeContext;
The Context API is a React feature that enables you to manage and share state across the entire component tree without having to pass props manually at every level. It is especially useful for managing global state such as user authentication, theme settings, or any other data that needs to be accessible throughout your application.
Key Components of Context API
Creating a Context
Start by creating a context object. This is usually done in a separate file.
// context/ThemeContext.js
import React from'react';
const ThemeContext = React.createContext();
export default ThemeContext;
Creating a Context Provider
Create a provider component that will hold the state and provide it to the rest of the application.|
importReact, { useState } from'react';
importThemeContextfrom'./ThemeContext';
constThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => { setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light')); };
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}> {children}
</ThemeContext.Provider> );
};
exportdefaultThemeProvider;
Consume the context value in any component that needs it.
importReact, { useContext } from'react'; importThemeContextfrom'../context/ThemeContext';
constThemeSwitcher = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button> </div> ); };
exportdefaultThemeSwitcher;
Wrap your application with the ThemeProvider
to make the context available throughout your component tree.
The Context API is a powerful and straightforward tool for managing global state in React and Next.js applications. By following the steps outlined above, you can efficiently share state across your component tree without the need for complex state management libraries. Whether you’re building a React app or working with Next.js, integrating the Context API can streamline your development process and enhance the maintainability of your code.