Skip to content

useContext

vinibiavatti1 edited this page Sep 28, 2026 · 2 revisions

Allows components to subscribe and read data from a nearest matching <Context> without passing props manually down through every level of the component tree (prop drilling). The use hook can also be used to read contexts.

Note: Whenever a Context value changes reference, all components consuming that Context will re-render. To prevent unnecessary re-renders across the tree, split unrelated data into smaller, domain-specific Contexts (e.g., AuthContext, ThemeContext) rather than using a single monolithic global object.

import { createContext, useContext } from 'react';

// Create context
export const ThemeContext = createContext('light');

// Provide context
export const Parent = () => {
    return (
        <ThemeContext value="dark">
            <MainContent />
        </ThemeContext>
    );
}

// Consume context
export const Child = () => {
    const theme = useContext(ThemeContext);
}

Clone this wiki locally