Popular Searches
Popular Course Categories
Popular Courses

useContext Hook

useContext Hook

Context API and State Sharing

useContext Hook in React

Course: React JS Training

Topic: useContext Hook

Course Link: JustAcademy React JS Training

Demo Link: Register for React JS Course Demo


1. Introduction to useContext Hook

The useContext Hook is a built-in React Hook that allows functional components to read and subscribe to a context value. It helps components access shared information without receiving that information through props at every intermediate level.

In React applications, several components may need the same information, such as the current user's details, theme settings, language preferences, or shopping cart data. Instead of passing this data through multiple components, you can use the Context API together with the useContext() Hook.

The useContext() Hook is commonly used with createContext() and a Context Provider.

Example

Suppose an application contains the following component structure:

App
 └── Dashboard
      └── Profile
           └── WelcomeMessage

If WelcomeMessage needs the current user's name, useContext() can access that information directly from a matching provider above it in the component tree.


2. What Is the useContext Hook?

useContext() is a React function that reads the value of a context object. It returns the value supplied by the closest matching provider above the component calling the Hook. If no matching provider exists, React returns the default value defined when the context was created.

Syntax

import { useContext } from "react";
const value = useContext(MyContext);

Explanation

  • useContext is the React Hook used to read context.
  • MyContext is a context object created with createContext().
  • value stores the value returned by the context.

Important: Call useContext() at the top level of a React component or custom Hook. Do not call it inside loops, conditions, or nested functions.


3. Why Do We Need useContext?

React normally passes data from parent components to child components through props. When deeply nested components need the same data, intermediate components may have to pass props even when they do not use them. This is known as prop drilling.

Example Without useContext

function App() {
  const userName = "Rahul";
  return <Dashboard userName={userName} />;
}
function Dashboard({ userName }) {
  return <Profile userName={userName} />;
}
function Profile({ userName }) {
  return <WelcomeMessage userName={userName} />;
}
function WelcomeMessage({ userName }) {
  return <h2>Welcome, {userName}!</h2>;
}

Here, Dashboard and Profile forward the userName prop even though they do not need it for their own display.

Solution With useContext

With Context API, a parent can provide the value once, and the deeply nested WelcomeMessage component can read it using useContext().


4. Main Parts of Context API

Part Purpose
createContext() Creates a context object.
Context Provider Provides a value to descendant components.
useContext() Reads the value from the closest matching provider.
useState() Manages changing values that can be shared through context.
useReducer() Manages more structured state updates that can be shared through context.

5. Creating a Context for useContext

Before using useContext(), create a context using createContext(). It is generally best to define the context outside component functions, often in a separate file.

Step 1: Create ThemeContext.jsx

import { createContext } from "react";
export const ThemeContext = createContext("light");

Here, ThemeContext is created with a default value of "light".

Step 2: Provide a Context Value

For React 19 and later:

<ThemeContext value="dark">
  <ThemeDisplay />
</ThemeContext>

For React 18 and earlier:

<ThemeContext.Provider value="dark">
  <ThemeDisplay />
</ThemeContext.Provider>

The provider makes the value "dark" available to components rendered inside it.


6. Basic Example of useContext

Let's create a simple React example that displays the current theme using the useContext() Hook.

ThemeContext.jsx

import { createContext } from "react";
export const ThemeContext = createContext("light");

ThemeDisplay.jsx

import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function ThemeDisplay() {
  const theme = useContext(ThemeContext);
  return <h2>Current Theme: {theme}</h2>;
}
export default ThemeDisplay;

App.jsx

For React 18 and earlier:

import { ThemeContext } from "./ThemeContext";
import ThemeDisplay from "./ThemeDisplay";
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemeDisplay />
    </ThemeContext.Provider>
  );
}
export default App;

Expected Output

Current Theme: dark

The component displays dark because that is the value supplied by the provider. React 19 projects can use the context object directly as the provider instead of ThemeContext.Provider.


7. Understanding the Default Value

The default value is the fallback value passed to createContext(). React uses it when no matching provider exists above the component reading the context.

Example

import { createContext, useContext } from "react";
const LanguageContext = createContext("English");
function LanguageDisplay() {
  const language = useContext(LanguageContext);
  return <p>Language: {language}</p>;
}
export default LanguageDisplay;

If LanguageDisplay is rendered without a matching provider, the output is:

Language: English

The default value is a static fallback. It does not automatically change when application data changes. To share changing values, provide state through a context provider.


8. Reading Different Types of Context Values

The useContext() Hook can return different kinds of JavaScript values depending on what the provider supplies.

Example 1: String Context

const ThemeContext = createContext("light");
const theme = useContext(ThemeContext);

Used for theme names or language labels.

Example 2: Number Context

const FontSizeContext = createContext(16);
const fontSize = useContext(FontSizeContext);

Used for numeric settings such as a preferred font size.

Example 3: Object Context

const UserContext = createContext(null);
const user = useContext(UserContext);

Used for shared user information or preferences. If the value can be null, check it before accessing its properties.

Example 4: Array Context

const SkillsContext = createContext([]);
const skills = useContext(SkillsContext);

Used for shared lists, such as a list of skills or categories.

Example 5: Function Context

const ActionsContext = createContext(null);
const actions = useContext(ActionsContext);

A context can also provide functions that descendant components can call to perform actions.


9. Sharing User Information with useContext

One common use of Context API is sharing user details across multiple components.

UserContext.jsx

import { createContext } from "react";
export const UserContext = createContext(null);

App.jsx

import { UserContext } from "./UserContext";
import UserProfile from "./UserProfile";
function App() {
  const user = {
    name: "Rahul Sharma",
    role: "Frontend Developer"
  };
  return (
    <UserContext.Provider value={user}>
      <UserProfile />
    </UserContext.Provider>
  );
}
export default App;

UserProfile.jsx

import { useContext } from "react";
import { UserContext } from "./UserContext";
function UserProfile() {
  const user = useContext(UserContext);
  if (!user) {
    return <p>No user information available.</p>;
  }
  return (
    <div>
      <h2>User Profile</h2>
      <p>Name: {user.name}</p>
      <p>Role: {user.role}</p>
    </div>
  );
}
export default UserProfile;

Expected Output

User Profile
Name: Rahul Sharma
Role: Frontend Developer

The UserProfile component accesses the user object through context instead of receiving it as a prop.


10. Updating Context Values with useState

The useContext() Hook reads a context value, but it does not change that value by itself. To update shared data, combine context with a state Hook such as useState().

Example: Theme Toggle

import { createContext, useContext, useState } from "react";
const ThemeContext = createContext("light");
function ThemeDisplay() {
  const theme = useContext(ThemeContext);
  return <h2>Current Theme: {theme}</h2>;
}
function App() {
  const [theme, setTheme] = useState("light");
  function toggleTheme() {
    setTheme(currentTheme =>
      currentTheme === "light" ? "dark" : "light"
    );
  }
  return (
    <ThemeContext.Provider value={theme}>
      <ThemeDisplay />
      <button onClick={toggleTheme}>Toggle Theme</button>
    </ThemeContext.Provider>
  );
}
export default App;

How It Works

  1. useState() stores the current theme.
  2. The provider supplies the current state through its value prop.
  3. ThemeDisplay reads the theme using useContext().
  4. Clicking the button updates the state.
  5. React provides the updated value to consumers, which re-render to reflect the change.

11. useContext with Multiple Contexts

A component can read more than one context. This is useful when a component needs different types of shared information, such as both the current theme and the current user.

Example

import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
const UserContext = createContext(null);
function Dashboard() {
  const theme = useContext(ThemeContext);
  const user = useContext(UserContext);
  return (
    <div>
      <p>Theme: {theme}</p>
      <p>User: {user ? user.name : "Guest"}</p>
    </div>
  );
}
function App() {
  const user = { name: "Rahul" };
  return (
    <ThemeContext.Provider value="dark">
      <UserContext.Provider value={user}>
        <Dashboard />
      </UserContext.Provider>
    </ThemeContext.Provider>
  );
}
export default App;

Expected Output

Theme: dark
User: Rahul

Each call to useContext() reads from the matching context independently.


12. Nested Providers and useContext

If multiple providers for the same context are nested, useContext() reads the value from the closest matching provider above the component.

Example

import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function ThemeDisplay() {
  const theme = useContext(ThemeContext);
  return <p>Theme: {theme}</p>;
}
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemeDisplay />
      <ThemeContext.Provider value="light">
        <ThemeDisplay />
      </ThemeContext.Provider>
    </ThemeContext.Provider>
  );
}
export default App;

Expected Output

Theme: dark
Theme: light

The first component reads from the outer provider, while the second reads from the inner provider.


13. Rules for Using useContext

  • Call useContext() at the top level of a React component or custom Hook.
  • Do not call it inside loops, conditions, or nested functions.
  • Pass the context object itself to useContext(), not the provider value or context name as a string.
  • Make sure the provider is above the component that reads the context.
  • Use the same context object when providing and reading the value.
  • Remember that a component cannot read a provider returned by that same component; the provider must be above the component calling the Hook.
  • Use state or a reducer when the shared value needs to change over time.

14. Advantages of useContext

  • Reduces unnecessary prop drilling.
  • Allows deeply nested components to read shared values.
  • Works with strings, numbers, objects, arrays, and functions.
  • Works with useState() and useReducer() to share dynamic data.
  • Supports multiple independent contexts within one application.
  • Is built into React and requires no additional library.
  • Can make application code easier to maintain when shared data is organized clearly.

15. Limitations of useContext

  • useContext() reads context; it does not independently manage or update state.
  • Components reading a context may re-render when its provided value changes.
  • Large contexts that combine unrelated data can make updates harder to manage.
  • Consumers outside a matching provider receive the context's default value.
  • Context does not automatically persist information after a page refresh.
  • It is not automatically the best solution for every type of application state.

16. Common useContext Errors and Solutions

Error Cause Solution
Default value appears unexpectedly The component is outside the matching provider. Check the provider placement and component tree.
Context value is undefined The provider may pass undefined or omit the intended value. Check the provider's value prop.
Hook is called conditionally The Rules of Hooks are violated. Call useContext() at the component's top level.
Context does not update as expected The provider's value may not be changing as intended. Check state updates and the provider's value.
Unexpected value from nested provider A closer provider overrides the outer provider. Check which provider is closest to the consumer.
Context appears different across files The provider and consumer may import different context objects. Export and import one shared context object.

17. useContext vs Props

Feature Props useContext
Purpose Pass data explicitly between components. Read shared data from context.
Deep component trees May require forwarding props through intermediate components. Allows descendant components to read context directly.
Setup Pass props to a child component. Create context, provide a value, and call the Hook.
Best suited for Local component configuration and explicit data flow. Values shared across multiple descendant components.
State updates Updated props can be passed from the parent. Consumers receive updates when the provided context value changes.

18. Mini Project: Language Selector with useContext

Objective: Create a small application that shares a language selection through context.

Step 1: Create LanguageContext.jsx

import { createContext } from "react";
export const LanguageContext = createContext("English");

Step 2: Create LanguageDisplay.jsx

import { useContext } from "react";
import { LanguageContext } from "./LanguageContext";
function LanguageDisplay() {
  const language = useContext(LanguageContext);
  return <h2>Selected Language: {language}</h2>;
}
export default LanguageDisplay;

Step 3: Update App.jsx

import { useState } from "react";
import { LanguageContext } from "./LanguageContext";
import LanguageDisplay from "./LanguageDisplay";
function App() {
  const [language, setLanguage] = useState("English");
  return (
    <LanguageContext.Provider value={language}>
      <LanguageDisplay />
      <button onClick={() => setLanguage("Hindi")}>
        Select Hindi
      </button>
      <button onClick={() => setLanguage("English")}>
        Select English
      </button>
    </LanguageContext.Provider>
  );
}
export default App;

Expected Output

Selected Language: English

When the user clicks Select Hindi, the displayed value changes to Hindi. Clicking Select English changes it back to English.

Learning Outcomes

  • Create and export a context object.
  • Provide a changing value using state.
  • Read the value using useContext().
  • Understand how context consumers receive updates.

19. Interview Questions and Answers

Q1. What is useContext in React?

Answer: useContext() is a React Hook that reads and subscribes to a context value.

Q2. What does useContext return?

Answer: It returns the value supplied by the closest matching provider above the component, or the context's default value if no matching provider exists.

Q3. Does useContext replace props?

Answer: No. Props are still useful for explicit communication between related components. Context is useful for values shared across a component subtree.

Q4. Can useContext update a value?

Answer: Not by itself. To update shared data, combine context with state Hooks such as useState() or useReducer().

Q5. What is prop drilling?

Answer: Prop drilling occurs when data is passed through intermediate components that do not need the data themselves.

Q6. Can useContext read multiple contexts?

Answer: Yes. A component can call useContext() separately for each context it needs.

Q7. What happens when a context value changes?

Answer: React re-renders components that read that context so they can use the updated value.

Q8. What happens when no provider exists?

Answer: The component receives the default value supplied to createContext().

Q9. Can useContext be used inside an if statement?

Answer: No. Like other Hooks, useContext() must be called at the top level of a component or custom Hook.

Q10. What is the difference between createContext and useContext?

Answer: createContext() creates a context object, while useContext() reads the value of that context inside a component.


20. Practice Exercises

  1. Create a ThemeContext and display its value using useContext().
  2. Create a UserContext that shares a user's name and role.
  3. Build a language selector that updates the context value using useState().
  4. Create separate contexts for theme and user information, and read both in one component.
  5. Create nested providers and observe how the closest provider determines the value.
  6. Write an example of prop drilling and refactor it using Context API.
  7. Explain what happens when a context consumer is rendered outside its provider.

21. Quick Revision Checklist

  • Understand the purpose and syntax of useContext().
  • Know how to create a context using createContext().
  • Understand how a provider supplies context values.
  • Know how to read strings, objects, and other values from context.
  • Understand default values and nested providers.
  • Know how to combine context with useState().
  • Follow the Rules of Hooks.
  • Understand common errors and best practices.
  • Build a mini project using Context API.

22. Conclusion

The useContext() Hook is an important React feature for reading shared data without passing props through every intermediate component. When combined with createContext(), a provider, and state Hooks, it helps developers share and update values such as themes, user details, and language preferences throughout an application.

Learn more through JustAcademy React JS Training and Register for React JS Course Demo.


23. Official React References

Previous Next
whatsapp