Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
🌍 Context API BasicsπŸ“¦ Creating ContextπŸ”Œ Context.ProviderπŸ” useContext Hook🎯 Passing Data with ContextπŸ”„ Context with useState⚑ Context PerformanceπŸ—οΈ Context Best Practices
Reactjs/Context/Usecontext Hook

πŸ” useContext Hook β€” Accessing Context Values

The `useContext` hook lets any component inside a Provider access the Context's value. It's the consumer side of Context.


🎯 Using useContext

To access a Context value, simply call `useContext()` with the Context object:

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function Header() {
  // Access the theme value
  const theme = useContext(ThemeContext);

  return <h1>Current theme: {theme}</h1>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Header />
    </ThemeContext.Provider>
  );
}
// Output: "Current theme: dark"

`useContext` always returns the value from the nearest Provider above it. If there's no Provider, it returns the initial value.

πŸ’‘ Accessing Object Values from Context

Most of the time, your Context holds an object with multiple values. You can destructure it:

import { createContext, useContext, useState } from "react";

const UserContext = createContext({ user: null, setUser: () => {} });

function UserProfile() {
  // Destructure the values you need
  const { user, setUser } = useContext(UserContext);

  if (!user) {
    return <p>No user logged in</p>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
}

<details>

<summary>πŸ“š More Examples</summary>

// Example 1: Accessing specific parts of context
const ConfigContext = createContext({
  apiUrl: "",
  timeout: 0,
});

function ApiClient() {
  // Only access what you need
  const { apiUrl } = useContext(ConfigContext);
  return <p>API: {apiUrl}</p>;
}

// Example 2: Using context value in effects and callbacks
function DataFetcher() {
  const { apiUrl, timeout } = useContext(ConfigContext);

  useEffect(() => {
    fetch(apiUrl, { signal: AbortSignal.timeout(timeout) })
      .then((res) => res.json())
      .then((data) => console.log(data));
  }, [apiUrl, timeout]);

  return <div>Fetching data...</div>;
}

</details>

🎨 Real-World Example: Language Switcher

Many apps need to display text in different languages. Use Context to share the current language:

import { createContext, useContext, useState } from "react";

type Language = "en" | "es" | "fr";

const LanguageContext = createContext({
  language: "en",
  setLanguage: (lang: Language) => {},
});

function LanguageSwitcher() {
  const { language, setLanguage } = useContext(LanguageContext);

  return (
    <div>
      <p>Current language: {language}</p>
      <button onClick={() => setLanguage("en")}>English</button>
      <button onClick={() => setLanguage("es")}>EspaΓ±ol</button>
      <button onClick={() => setLanguage("fr")}>FranΓ§ais</button>
    </div>
  );
}

function GreetingMessage() {
  const { language } = useContext(LanguageContext);

  const greetings = {
    en: "Hello!",
    es: "Β‘Hola!",
    fr: "Bonjour!",
  };

  return <h1>{greetings[language]}</h1>;
}

function App() {
  const [language, setLanguage] = useState("en");

  return (
    <LanguageContext.Provider value={{ language, setLanguage }}>
      <LanguageSwitcher />
      <GreetingMessage />
    </LanguageContext.Provider>
  );
}

πŸ“Š useContext vs Props

AspectPropsuseContext
AccessPassed to componentAccessed with hook
Levels neededAll intermediate levelsJust direct access
UpdatesRerenders when props changeRerenders when context changes
Best forDirect relationshipsApp-wide data

πŸ”‘ Key Takeaways

  • βœ… `useContext()` accesses Context values inside components
  • βœ… Call `useContext()` with the Context object you want to access
  • βœ… Components must be inside the Provider to use the Context
  • βœ… You can destructure object values from Context
  • βœ… Accessing Context causes re-renders when the value changes
  • βœ… Use Context for data many components need
  • βœ… Avoid using Context for data that changes very frequently

Ready to practice? Challenges | Next: Passing Data with Context


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep β€’ Build Real β€’ Verify Skills β€’ Launch Forward

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn