← Back to Chapters

useContext() Hook

⚛️ useContext() Hook

? Quick Overview

The useContext() hook is the modern, convenient way to read shared data from a React context inside any function component. It replaces the older Context.Consumer pattern and keeps your components clean and readable.

Think of useContext() as a direct portal to global data like theme, language, or logged-in user — without manually passing props down every level.

✨ Best for: Global / shared state in function components

? Key Concepts

  • Context lets you share data across component trees without prop drilling.
  • useContext(Context) reads the current value from the nearest matching Provider.
  • Components using useContext() automatically re-render when the context value changes.
  • Always use useContext() inside React function components or custom hooks.

? Syntax & Basic Usage

The basic syntax of useContext() looks like this:

? View Code Example
// Read the current value of a context
const value = useContext(MyContext);
  • MyContext is the context object created using createContext().
  • value will be whatever you passed to the matching <MyContext.Provider value={...} />.
  • If there is no Provider above, the default value from createContext(defaultValue) is used.

? Example: Building a Theme Context with useContext

Let’s build a simple ThemeContext to share the current theme and a function to toggle it.

1️⃣ Creating the Context (ThemeContext.js)

? View Code Example
// ThemeContext.js - defines a shared theme context
import { createContext } from "react";

const ThemeContext = createContext("light");

export default ThemeContext;

2️⃣ Providing the Context (App.js)

? View Code Example
// App.js - wraps children with ThemeContext.Provider
import React, { useState } from "react";
import ThemeContext from "./ThemeContext";
import Toolbar from "./Toolbar";

function App() {
const [theme, setTheme] = useState("light");

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

export default App;

3️⃣ Consuming the Context with useContext (Toolbar.js)

? View Code Example
// Toolbar.js - reads and updates theme using useContext
import React, { useContext } from "react";
import ThemeContext from "./ThemeContext";

function Toolbar() {
const { theme, setTheme } = useContext(ThemeContext);

return (
<div className={`p-3 text-center bg-${theme === "light" ? "light" : "dark"} text-${theme === "light" ? "dark" : "light"}`}>
<p>Current Theme: {theme}</p>
<button
className="btn btn-primary"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
>
Toggle Theme
</button>
</div>
);
}

export default Toolbar;

? Live Output (Conceptual)

Initial UI:

  • Background is light and text is dark.
  • Message shows: Current Theme: light

After clicking “Toggle Theme”:

  • Theme flips to dark mode (background dark, text light).
  • Message updates to: Current Theme: dark
  • Both changes are driven by the shared context value.

? Comparison: useContext vs Context.Consumer

Both approaches read from context, but useContext() is cleaner in modern React apps.

Aspect useContext Hook Context.Consumer
Syntax Simple hook call Render-prop function
Code Length Short & clean Verbose & nested
Hooks Support ✅ Works in function components ✅ Works in class & function (but older style)
Performance Efficient, fewer nested components Can cause extra nesting
Preferred Usage Modern React apps (Hooks) Legacy / pre-Hooks codebases

? Multiple Contexts Example

You can combine multiple contexts by calling useContext() several times within the same component. This is useful when you want to share theme, authentication, language, etc. together.

? View Code Example
// Dashboard.js - consuming multiple contexts
import React, { useContext } from "react";
import ThemeContext from "./ThemeContext";
import AuthContext from "./AuthContext";

function Dashboard() {
const { theme } = useContext(ThemeContext);
const { user } = useContext(AuthContext);

return (
<div className={`p-3 bg-${theme}`}>
<h4>Welcome, {user ? user.name : "Guest"}!</h4>
</div>
);
}

export default Dashboard;

? What’s Happening?

  • ThemeContext controls the background appearance.
  • AuthContext provides the current user object.
  • If the user is not logged in, the UI falls back to "Guest".
  • This keeps theme and auth logic centralized and reusable.

? Use Cases for useContext

  • Theme (light / dark mode, colors, layout preferences).
  • Authentication (current user, roles, permissions).
  • Localization (current language, date/number formats).
  • Global app settings (feature flags, config values).
  • Shopping cart or global filters in medium-sized apps.

⚙️ Key Points & Best Practices

  • Call useContext() only at the top level of your component or custom hook.
  • Never call useContext() inside loops, conditions, or nested functions.
  • If multiple providers are used, the nearest one in the component tree wins.
  • Do not use useContext() outside a matching Provider — it will fall back to the default value.
  • Keep context values as small and stable as possible to reduce unnecessary re-renders.

? Summary Table

Concept Description
useContext(Context) Returns the current value of a context
Re-renders Triggers when the Provider's value changes
Usage Best suited for React function components
Replaces Most uses of older Context.Consumer syntax

? Tips & Best Practices

  • Keep the context value simple — avoid very large or frequently changing objects.
  • Extract context logic into a custom hook (e.g., useTheme()) for cleaner components.
  • Combine multiple contexts using nested Providers for scalability and clarity.
  • Use context only for truly shared global data, not for every small prop.
  • Consider splitting contexts (e.g., read-only vs updater) to minimize re-renders.

? Try It Yourself

  1. Create a LanguageContext that stores { language, setLanguage }.
  2. Wrap your app with <LanguageContext.Provider> and default the language to "English".
  3. Build a Header component that uses useContext(LanguageContext) to show the current language.
  4. Add a button in Header to toggle between "English" and "Hindi".

Goal: Practice using useContext() for easy, clean access to shared global data in React components.

? View Practice Starter Code
// Starter idea for LanguageContext practice
import React, { createContext, useState, useContext } from "react";

const LanguageContext = createContext({ language: "English", setLanguage: () => {} });

function LanguageProvider({ children }) {
const [language, setLanguage] = useState("English");
return (
<LanguageContext.Provider value={{ language, setLanguage }}>
{children}
</LanguageContext.Provider>
);
}

function Header() {
const { language, setLanguage } = useContext(LanguageContext);
return (
<header>
<p>Current language: {language}</p>
<button onClick={() => setLanguage(language === "English" ? "Hindi" : "English")}>
Toggle Language
</button>
</header>
);
}

export { LanguageProvider, LanguageContext, Header };