In React, context provides a way to share values like state and functions between components without having to pass props down manually at every level. Creating a custom context provider is a great way to manage complex state or functionality that needs to be accessed by many components. In this article, we will explore three diverse examples of creating a custom context provider in React.
In this example, we’ll create a Theme Context Provider that allows components to toggle between light and dark themes. This is a common scenario in modern web applications where user preferences for themes enhance user experience.
import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
export 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>
);
};
export const useTheme = () => useContext(ThemeContext);
<ThemeProvider>
.const { theme, toggleTheme } = useTheme();
to access and toggle the theme.This example shows how to create an Auth Context Provider to manage user authentication state. This is essential for applications that require user login functionality.
import React, { createContext, useState, useContext } from 'react';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const login = (username) => {
// Simulate a login API call
setUser({ name: username });
};
const logout = () => {
setUser(null);
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
<AuthProvider>
.const { user, login, logout } = useAuth();
in your components to manage authentication.In e-commerce applications, managing a shopping cart state is crucial. This example demonstrates how to create a Cart Context Provider to handle adding and removing items from the cart.
import React, { createContext, useState, useContext } from 'react';
const CartContext = createContext();
export const CartProvider = ({ children }) => {
const [cart, setCart] = useState([]);
const addToCart = (item) => {
setCart((prevCart) => [...prevCart, item]);
};
const removeFromCart = (itemId) => {
setCart((prevCart) => prevCart.filter(item => item.id !== itemId));
};
return (
<CartContext.Provider value={{ cart, addToCart, removeFromCart }}>
{children}
</CartContext.Provider>
);
};
export const useCart = () => useContext(CartContext);
<CartProvider>
.const { cart, addToCart, removeFromCart } = useCart();
in components to manipulate the shopping cart.By implementing these custom context providers, you can manage state in a clean and efficient manner across your React application, improving both code organization and user experience.