Custom Context Provider in React: 3 Examples

Explore practical examples of creating custom context providers in React to manage state effectively across your application.
By Taylor

Introduction to Custom Context Providers in React

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.

Example 1: Theme Context Provider

Use Case

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);

Notes

  • To use this provider, wrap your main app component with <ThemeProvider>.
  • Inside any component, you can call const { theme, toggleTheme } = useTheme(); to access and toggle the theme.

Example 2: Auth Context Provider

Use Case

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);

Notes

  • Wrap your application with <AuthProvider>.
  • You can use const { user, login, logout } = useAuth(); in your components to manage authentication.

Example 3: Cart Context Provider

Use Case

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);

Notes

  • Don’t forget to wrap your app with <CartProvider>.
  • Use 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.