SyntaxStudy
Sign Up
React Creating and Providing Context
React Beginner 1 min read

Creating and Providing Context

React Context solves prop-drilling: the need to pass data through many layers of components that do not themselves use the data, just to get it to a deeply nested descendant. createContext creates a context object that carries a default value used when no matching Provider is found above in the tree. The Provider component accepts a value prop. Every component inside the Provider that reads this context will receive the current value and will re-render whenever value changes. This makes Context an excellent home for truly global, cross-cutting concerns: the authenticated user, the current locale, the active colour theme, or a global notification queue. Context is not a replacement for all state management. For data that is truly local to a subtree, or data that changes very frequently, lifting state or using a dedicated library like Zustand or Redux is often a better fit.
Example
import { createContext, useContext, useState } from 'react';

// 1. Create context with a sensible default
const ThemeContext = createContext({
    theme: 'light',
    toggleTheme: () => {},
});

// 2. Provider component
export function ThemeProvider({ children }) {
    const [theme, setTheme] = useState('light');

    function toggleTheme() {
        setTheme(t => (t === 'light' ? 'dark' : 'light'));
    }

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    );
}

// 3. Consumer — any depth in the tree
function ThemedButton({ children }) {
    const { theme, toggleTheme } = useContext(ThemeContext);

    return (
        <button
            onClick={toggleTheme}
            style={{
                background: theme === 'light' ? '#fff' : '#222',
                color:      theme === 'light' ? '#222' : '#fff',
            }}
        >
            {children}
        </button>
    );
}

// 4. App root
export default function App() {
    return (
        <ThemeProvider>
            <ThemedButton>Toggle Theme</ThemedButton>
        </ThemeProvider>
    );
}