useContext in React: A Practical Tutorial with Runnable Examples
Build shared React preferences without prop drilling. Follow complete JSX examples, provider behaviour, and output questions.
KnowledgeGate Team
Exam prep & CS education

Passing theme, fontSize, and update functions through App -> Toolbar -> ProfilePanel -> SaveButton makes intermediate components carry unused props. This prop drilling makes a growing tree harder to change. createContext, a provider, and useContext replace that chain without turning every value into global state. The Coding Skills category provides the broader frontend path.
1. What useContext solves, and what it does not
Context is a value made available to a component subtree. As the official React useContext reference explains, createContext creates the context object, a provider supplies a value, and useContext(SomeContext) reads and subscribes to the closest matching provider above the caller.
Scope still matters. Keep isMenuOpen local. Pass label="Save" when only one child needs it. Consider context for { theme: "dark", fontSize: 16 } used several levels down. Context transports state, but it does not replace useState, reducers, or server-data tools. React Hooks Explained surveys state, effects, memoisation, and custom Hooks; useContext specifically depends on Context lookup, provider boundaries, and value updates.
2. Build the smallest runnable useContext example
Put this in App.jsx. SaveButton receives no theme prop, yet it reads the value supplied above Toolbar.
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function SaveButton() {
const theme = useContext(ThemeContext);
return <button className={`button-${theme}`}>Save ({theme})</button>;
}
function Toolbar() {
return <SaveButton />;
}
function PreviewButton() {
const theme = useContext(ThemeContext);
return <button className={`button-${theme}`}>Preview ({theme})</button>;
}
export default function App() {
return <>
<ThemeContext.Provider value="dark"><Toolbar /></ThemeContext.Provider>
<PreviewButton />
</>;
}The first button renders Save (dark) with button-dark. PreviewButton is outside the provider, so it uses the fallback only because no matching provider is above it. It renders Preview (light) with button-light. Current React documentation shows <ThemeContext value={...}> for React 19 and identifies .Provider as the older form. The .Provider form remains compatible with React versions that predate the shorter provider syntax.
3. Worked example: share and update exact preferences
Build the complete example as five files.
// PreferencesContext.js
import { createContext } from "react";
export const PreferencesContext = createContext(null);
// PreferencesProvider.jsx
import { useState } from "react";
import { PreferencesContext } from "./PreferencesContext";
export function PreferencesProvider({ children }) {
const [theme, setTheme] = useState("dark");
const [fontSize, setFontSize] = useState(16);
const toggleTheme = () => setTheme(t => t === "dark" ? "light" : "dark");
const increaseFont = () => setFontSize(size => Math.min(size + 2, 20));
const value = { theme, fontSize, toggleTheme, increaseFont };
return <PreferencesContext.Provider value={value}>{children}</PreferencesContext.Provider>;
}
// ProfilePanel.jsx
import { useContext } from "react";
import { PreferencesContext } from "./PreferencesContext";
export function ProfilePanel() {
const { theme, fontSize, toggleTheme, increaseFont } = useContext(PreferencesContext);
return <section>
<p>Theme: {theme} | Text: {fontSize}px</p>
<button onClick={increaseFont}>Increase text</button>
<button onClick={toggleTheme}>Toggle theme</button>
</section>;
}
// SaveButton.jsx
import { useContext } from "react";
import { PreferencesContext } from "./PreferencesContext";
export function SaveButton() {
const { theme } = useContext(PreferencesContext);
return <button>Save in {theme} mode</button>;
}
// App.jsx
import { PreferencesProvider } from "./PreferencesProvider";
import { ProfilePanel } from "./ProfilePanel";
import { SaveButton } from "./SaveButton";
function Toolbar() {
return <><ProfilePanel /><SaveButton /></>;
}
export default function App() {
return <PreferencesProvider><Toolbar /></PreferencesProvider>;
}The first render shows Theme: dark | Text: 16px and Save in dark mode. Text clicks compute min(16 + 2, 20) = 18, then min(18 + 2, 20) = 20, then min(20 + 2, 20) = 20. The sequence is 16px -> 18px -> 20px -> 20px. Toggle theme changes both consumers to Theme: light | Text: 20px and Save in light mode. Toolbar receives no preference props.

4. The closest provider wins
Suppose an outer provider supplies { theme: "dark", fontSize: 16 }. MainToolbar below it renders dark / 16px. If only SettingsModal gets a nested provider with { theme: "light", fontSize: 14 }, its ModalSaveButton renders light / 14px. React searches upward from each consumer and stops at the closest matching provider.
Absence is different from undefined. With createContext("light"), no provider gives the consumer "light". A matching provider with value={undefined} gives it undefined, not the fallback, as React's troubleshooting guidance notes.
There is also a hierarchy trap. A component's own useContext call cannot see a provider that the same component returns below that call. Move the provider to a parent, or move the consumer into a child.

5. What changes cause consumers to render again
React documents the core rule: consumers receive the latest value when a provider's value changes. It compares values with Object.is; memo cannot block fresh context. Thus { dark, 16 } -> { dark, 18 } updates size, while { dark, 20 } -> { light, 20 } updates both theme strings.
Every provider render can create a new object and new function identities. After correctness, and only when measurement shows unnecessary consumer renders, stabilise them:
const toggleTheme = useCallback(
() => setTheme(t => t === "dark" ? "light" : "dark"), []
);
const increaseFont = useCallback(
() => setFontSize(size => Math.min(size + 2, 20)), []
);
const value = useMemo(
() => ({ theme, fontSize, toggleTheme, increaseFont }),
[theme, fontSize, toggleTheme, increaseFont]
);Import useCallback and useMemo from React. This is an optimisation for a measured problem, not compulsory boilerplate for every small provider. useMemo and useCallback in React compares cached values and stable functions with render counts. Stable identities prevent a provider from broadcasting an unchanged object.
6. Common useContext errors and their fixes
Calling
useContextinsideif (loggedIn)breaks the Hooks rule. Call it unconditionally at the top level.A provider below or inside the caller leaves that caller on the fallback. Move it above.
Forgetting
valuegives the consumerundefined. Pass the exactvalueprop.Creating two
PreferencesContextobjects means provider and consumer do not match, even if the variables share a name. Export one object fromPreferencesContext.jsand import it everywhere.Putting
isTooltipOpenor every form keystroke in a broad app context creates needless coupling. Keep state close, then lift it only when several distant descendants need it.
A rarer failure occurs when duplicate modules produce separate context objects. React documents it, but first check provider position and imports.
7. Check understanding with output questions and one exercise
Predict each output and give a one-line reason: no provider with default "light"; outer {dark, 16} plus inner {light, 14} for the modal; and a provider with value={undefined}. The answers are light, light / 14px, and undefined, based on absence, closest provider, and explicit value respectively.
Now create NotificationContext with { build: 2, review: 3 }. Make NotificationBadge show 5 unread, and let markRead("build") produce { build: 0, review: 3 } and 3 unread. Pass nothing through Header:
import { createContext, useContext, useState } from "react";
const NotificationContext = createContext(null);
function NotificationBadge() {
const { unread, markRead } = useContext(NotificationContext);
return <button onClick={() => markRead("build")}>
{unread.build + unread.review} unread
</button>;
}
function Header() { return <NotificationBadge />; }
export default function App() {
const [unread, setUnread] = useState({ build: 2, review: 3 });
const markRead = key => setUnread(v => ({ ...v, [key]: 0 }));
return <NotificationContext.Provider value={{ unread, markRead }}><Header /></NotificationContext.Provider>;
}The totals are 2 + 3 = 5 and 0 + 3 = 3.
8. Short version and the next step
Create the context, provide a value above the subtree, read it with useContext, and keep updating state in the provider. In the worked sequence, that leaves { theme: "light", fontSize: 20 } visible to both consumers. Continue with the React and Redux course for guided practice. For measured fan-out and splitting state from actions, React Context Boundaries applies the lookup and identity rules to boundary design and render-count experiments.
Keep learning
Normalization in SQL: A Practical 1NF-to-3NF Tutorial with Runnable Examples
Take one denormalized order table from 1NF through 2NF and 3NF. Build constrained tables, migrate four rows safely, and prove the joins preserve the data.
Classes in JavaScript: A Practical Tutorial with Runnable Examples
Learn what class syntax adds to JavaScript by building and extending a BankAccount. Trace exact values, repair common mistakes, and finish with three exercises.
React Events Tutorial: onClick, Forms and Runnable Examples
Build one PracticeTracker component, follow every click, change and submit, then learn exactly when to use preventDefault and stopPropagation.
Conditional Rendering in React: 5 Patterns with Runnable Examples
Learn when to use early returns, ternaries, logical AND, null, and switch through a course dashboard you can run and test with five UI states.





