Popular Searches
Popular Course Categories
Popular Courses

useContext Hook

useContext Hook

Context API and State Sharing

useContext Hook in React JS

useContext Hook is a built-in React Hook that allows a functional component to read and subscribe to a context value. It helps share data between components without manually passing props through every intermediate component. It is commonly used for themes, user authentication, language preferences, and shared application settings.

Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is the useContext Hook?

The useContext() Hook lets a component access a value from a React Context. Instead of passing data from a parent to a child through multiple levels of props, a component can read the shared value directly from the nearest matching context provider above it.

Syntax

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

Explanation

  • useContext is imported from React.
  • MyContext is a context object created using createContext().
  • value stores the context value returned by the Hook.

2. Why Do We Need useContext?

In React, props are commonly used to pass data from parent components to child components. However, if deeply nested components need the same information, props may need to pass through components that do not use the data themselves. This is called prop drilling.

Example Without useContext

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

In this example, the Profile component receives and forwards the username even though it does not need to display it.

Example Using useContext

import { createContext, useContext } from "react";
const UserContext = createContext("Guest");
function UserDetails() {
  const username = useContext(UserContext);
  return <h2>Welcome, {username}!</h2>;
}
function App() {
  return (
    <UserContext value="Rahul">
      <UserDetails />
    </UserContext>
  );
}
export default App;

Output: Welcome, Rahul!

For React versions before React 19, replace with and use the corresponding closing tag.


3. How Does useContext Work?

The useContext() Hook reads the value supplied by the nearest matching provider above the component that calls it. If no matching provider exists, React returns the default value defined when the context was created.

Working Steps

  1. Create a context using createContext().
  2. Provide a value using the matching context provider.
  3. Import the context into the component that needs the data.
  4. Call useContext(MyContext) inside that component.
  5. Use the returned value in the component's JSX or logic.
  6. If the provided value changes, React updates components that read that context.

Flow Diagram

createContext()
      |
      v
Context Object
      |
      v
Context Provider
      |
      v
Child Component
      |
      v
useContext(MyContext)
      |
      v
Access Shared Value

4. Creating Context Before Using useContext

Before reading a context, you must create it using React's createContext() function.

ThemeContext.js

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

Here, ThemeContext is created with a default value of "light". This default is used only when no matching provider exists above the component reading the context.


5. Basic Example of useContext

In this example, a component reads a theme value from Context.

App.jsx

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

Output

Current Theme: dark

The Header component receives the value "dark" because it is inside the matching provider.


6. useContext with a Separate Context File

In a larger React application, it is often useful to define Context in a separate file so multiple components can import and use the same context object.

Project Structure

src/
  context/
    UserContext.js
  components/
    Profile.jsx
  App.jsx

Step 1: Create UserContext.js

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

Step 2: Create Profile.jsx

import { useContext } from "react";
import UserContext from "../context/UserContext";
function Profile() {
  const username = useContext(UserContext);
  return <h2>Welcome, {username}!</h2>;
}
export default Profile;

Step 3: Use Context in App.jsx

import UserContext from "./context/UserContext";
import Profile from "./components/Profile";
function App() {
  return (
    <UserContext value="Rahul">
      <Profile />
    </UserContext>
  );
}
export default App;

For React versions before React 19, use UserContext.Provider instead of rendering UserContext directly as the provider.


7. useContext with useState

Context can provide dynamic data when combined with the useState() Hook. When the state changes, the provider supplies the new value to the components that consume that context.

Example: Theme Switcher

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");
  const toggleTheme = () => {
    setTheme(previousTheme =>
      previousTheme === "light" ? "dark" : "light"
    );
  };
  return (
    <ThemeContext value={theme}>
      <ThemeDisplay />
      <button onClick={toggleTheme}>Toggle Theme</button>
    </ThemeContext>
  );
}
export default App;

For React versions before React 19: Use and its matching closing tag.

How It Works

  • useState("light") initializes the theme.
  • The provider supplies the current theme through value={theme}.
  • The button calls toggleTheme() to update the state.
  • React updates the provider value after the state changes.
  • ThemeDisplay receives the new value through useContext().

8. useContext with an Object

Context can provide an object containing multiple related values, such as a user's name, role, and email address.

Example

import { createContext, useContext } from "react";
const UserContext = createContext({
  name: "Guest",
  role: "Visitor"
});
function Profile() {
  const user = useContext(UserContext);
  return (
    <div>
      <h2>Name: {user.name}</h2>
      <p>Role: {user.role}</p>
    </div>
  );
}
function App() {
  const user = {
    name: "Rahul",
    role: "Student"
  };
  return (
    <UserContext value={user}>
      <Profile />
    </UserContext>
  );
}
export default App;

Output: Name: Rahul; Role: Student.

For React versions before React 19, use .


9. useContext with Multiple Contexts

A component can read more than one context. This is useful when different types of shared information are managed separately.

Example

import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
const LanguageContext = createContext("English");
function Dashboard() {
  const theme = useContext(ThemeContext);
  const language = useContext(LanguageContext);
  return (
    <div>
      <p>Theme: {theme}</p>
      <p>Language: {language}</p>
    </div>
  );
}
function App() {
  return (
    <ThemeContext value="dark">
      <LanguageContext value="Hindi">
        <Dashboard />
      </LanguageContext>
    </ThemeContext>
  );
}
export default App;

The Dashboard component can access both the theme and language values. For React versions before React 19, use the corresponding .Provider syntax.


10. Default Value in useContext

The default value is supplied when creating a context. React uses it when there is no matching provider above the component calling useContext().

Example

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

If Language is rendered without a matching provider, the output is Language: English.

Important: The default value is a static fallback. If a provider exists and supplies undefined, useContext() returns undefined instead of using the default value.


11. Rules of the useContext Hook

  • Call useContext() at the top level of a React function component or custom Hook.
  • Do not call it inside loops, conditions, or nested functions.
  • Pass the context object itself to useContext(), not the provider or its value.
  • The provider must be above the component that reads the context.
  • Use the same context object for both providing and reading the value.
  • When the provider value changes, React re-renders components that consume that context.

12. Common Uses of useContext

  • Theme management: Share light and dark theme settings.
  • Authentication: Share the current user or authentication status.
  • Language settings: Share the selected language across components.
  • Shopping cart: Share cart information and related actions.
  • User preferences: Share settings such as font size and display options.
  • Application configuration: Make common configuration values available throughout a component tree.

13. Advantages of useContext

  • Reduces prop drilling.
  • Makes shared data easier to access in nested components.
  • Works with different data types, including objects and functions.
  • Can be combined with useState() or useReducer() for dynamic shared state.
  • Helps organize common application settings.

14. Limitations and Performance Considerations

  • Context is not necessary for every piece of data; props are often simpler for nearby components.
  • Components consuming a context may re-render when its provided value changes.
  • Passing a newly created object or function as the context value on every render can cause additional re-renders.
  • Large applications may benefit from separating unrelated values into different contexts.
  • Context does not automatically persist data between page reloads or replace a backend database.

Performance Tip

If profiling shows unnecessary re-renders caused by frequently recreated objects or functions, consider useMemo() and useCallback() where appropriate. These are optimizations and should be used when they solve an actual performance issue.


15. Common Mistakes and Solutions

Mistake Solution
Forgetting to import useContext. Import it from react.
Passing the wrong context object. Use the same context instance that the provider uses.
Rendering a component outside its provider. Place the component inside the matching provider or use the default value intentionally.
Expecting the default value to update. Use state and pass the current value through the provider.
Calling useContext() inside a condition. Call the Hook at the top level of the component.
Forgetting the provider's value prop. Pass the intended value using value={...}.
Expecting a provider returned by the same component to affect that component's own Hook call. Read the context from a descendant component inside the provider.

16. Difference Between createContext() and useContext()

createContext() useContext()
Creates a context object. Reads and subscribes to a context value.
Usually called outside components. Called at the top level of a function component or custom Hook.
Example: createContext("light") Example: useContext(ThemeContext)
Defines the default fallback value. Returns the value from the nearest matching provider above the consumer, or the default if no provider exists.

17. Interview Questions and Answers

Q1. What is the useContext Hook?

useContext() is a React Hook that lets a component read and subscribe to a context value.

Q2. Why is useContext used?

It helps components access shared information without manually passing props through every intermediate component.

Q3. Which function is used to create Context?

The createContext() function is used to create a context object.

Q4. What does useContext() return?

It returns the value from the nearest matching provider above the component, or the context's default value if no matching provider exists.

Q5. Can useContext read updated values?

Yes. When a provider's value changes, React updates components that consume that context.

Q6. Can a component use multiple contexts?

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

Q7. What happens if a component is outside the provider?

It receives the context's default value if no matching provider exists above it.

Q8. Is useContext a replacement for props?

No. Props remain useful for explicit parent-to-child data flow. Context is most useful when many components need access to the same value.

Q9. Can useContext work with useState?

Yes. A provider can pass a state value, allowing descendant components to receive updates when the state changes.

Q10. What are common use cases for useContext?

Common examples include theme settings, authentication information, language preferences, and shared application configuration.


18. Practice Exercises

  1. Create a ThemeContext with a default value of "light".
  2. Use useContext() to display the current theme in a child component.
  3. Create a UserContext that shares a user's name and role.
  4. Build a button that changes the theme using useState() and Context.
  5. Create separate contexts for theme and language settings.
  6. Render a component outside its provider and observe the default value.
  7. Explain how Context helps reduce prop drilling.

19. Quick Revision Checklist

  • Understand the purpose of the useContext() Hook.
  • Know how to create a context using createContext().
  • Know how to read a context using useContext(MyContext).
  • Understand provider values and default values.
  • Know how to combine Context with useState().
  • Understand the rules of Hooks.
  • Know common uses, limitations, and performance considerations.
  • Understand the difference between createContext() and useContext().

20. Conclusion

The useContext() Hook is an important part of React Context API. It allows components to read shared values from the nearest matching provider and helps reduce prop drilling. When combined with createContext() and state management, it provides a practical way to share themes, user information, language settings, and other application data.

Official React Documentation: useContext Hook | Passing Data Deeply with Context

Learn React JS: JustAcademy React JS Training Course

Register for a Demo: Register for React JS Course Demo

whatsapp