Popular Searches
Popular Course Categories
Popular Courses

useContext Hook

useContext Hook

React Hooks Fundamentals

useContext Hook in React JS – Complete Detailed Notes

The useContext Hook is a built-in React Hook that allows functional components to access data shared by a parent component without passing props through every intermediate component. It is commonly used for managing themes, authenticated user information, language preferences, and application-wide settings.

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


1. What Is the useContext Hook?

In React, components often need to share information. Normally, data can be passed from a parent component to a child component through props. However, when many components need the same information, passing props through every intermediate component can become difficult. This is known as prop drilling.

The useContext Hook helps solve this problem by allowing components to read shared data from the nearest matching Context Provider above them in the component tree.

Basic syntax

import { createContext, useContext } from 'react';

const MyContext = createContext('Default Value');

function MyComponent() {
  const value = useContext(MyContext);

  return <p>{value}</p>;
}

Here, createContext() creates a Context object, while useContext() reads the value provided by the nearest matching provider above the component.


2. Why Do We Use useContext?

The useContext Hook is useful when multiple components need access to the same data without receiving it through multiple layers of props.

  • Theme management: Share light and dark theme preferences.
  • User authentication: Share the current user's information across components.
  • Language preferences: Share the selected application language.
  • Shopping cart: Share cart items and related actions.
  • Application settings: Share preferences such as layout or display options.
  • Permissions: Make user roles or permission information available to relevant components.

Context is useful for sharing data across a component tree, but it is not necessary for every value. Local state and props are often simpler when data is needed by only a few nearby components.


3. Understanding React Context

React Context provides a way to make a value available to components deep within a component tree. A Context object does not itself store changing application state. Instead, a provider supplies the current value, and components read that value using useContext.

Three important concepts

Concept Purpose
createContext() Creates a Context object and specifies its default value.
Context Provider Makes a value available to descendant components.
useContext() Reads the value from the nearest matching provider above the component.

Example of creating a Context

import { createContext } from 'react';

const ThemeContext = createContext('light');

export default ThemeContext;

In this example, ThemeContext is created with 'light' as its default value. If a component reads this context without a matching provider above it, React returns this default value.


4. Basic Example of useContext

Let's create a simple application in which a parent component provides a username and a child component displays it.

import { createContext, useContext } from 'react';

const UserContext = createContext('Guest');

function UserProfile() {
  const username = useContext(UserContext);

  return <h2>Welcome, {username}!</h2>;
}

function App() {
  return (
    <UserContext value="Manish">
      <UserProfile />
    </UserContext>
  );
}

export default App;

Explanation

  1. createContext('Guest') creates the UserContext with a default value.
  2. The App component provides the value "Manish".
  3. UserProfile calls useContext(UserContext).
  4. React finds the nearest UserContext provider above UserProfile.
  5. The component displays Welcome, Manish!.

Version note: The example uses the React 19 provider syntax, <UserContext value="Manish">. In React 18 and earlier, use <UserContext.Provider value="Manish"> instead.


5. What Is Prop Drilling?

Prop drilling happens when data is passed through intermediate components that do not need to use it themselves, simply so that a deeply nested component can access it.

Example without Context

function App() {
  const username = 'Manish';

  return <Dashboard username={username} />;
}

function Dashboard({ username }) {
  return <Profile username={username} />;
}

function Profile({ username }) {
  return <h2>Welcome, {username}!</h2>;
}

In this example, Dashboard receives and forwards username even though it may not need the value itself.

Example using Context

import { createContext, useContext } from 'react';

const UserContext = createContext('Guest');

function App() {
  return (
    <UserContext value="Manish">
      <Dashboard />
    </UserContext>
  );
}

function Dashboard() {
  return <Profile />;
}

function Profile() {
  const username = useContext(UserContext);

  return <h2>Welcome, {username}!</h2>;
}

export default App;

Now Dashboard does not need to receive or forward the username prop. Profile reads the value directly from Context.


6. Creating and Providing Context Step by Step

For a larger React application, Context is often placed in a separate file so that multiple components can import and use it.

Step 1: Create the Context

// ThemeContext.js
import { createContext } from 'react';

const ThemeContext = createContext('light');

export default ThemeContext;

Step 2: Provide a value

// App.jsx
import ThemeContext from './ThemeContext';
import Header from './Header';

function App() {
  return (
    <ThemeContext value="dark">
      <Header />
    </ThemeContext>
  );
}

export default App;

For React 18 and earlier, replace the provider element with <ThemeContext.Provider value="dark"> and close it with </ThemeContext.Provider>.

Step 3: Read the Context value

// Header.jsx
import { useContext } from 'react';
import ThemeContext from './ThemeContext';

function Header() {
  const theme = useContext(ThemeContext);

  return <header>Current Theme: {theme}</header>;
}

export default Header;

The Header component receives the value from the nearest ThemeContext provider above it.


7. useContext With useState

Context values can change over time. To make a value dynamic, store it in state in a parent component and pass the current state value through the Context Provider.

Example: Switch Between Light and Dark Themes

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

const ThemeContext = createContext('light');

function ThemeDisplay() {
  const theme = useContext(ThemeContext);

  return (
    <div>
      <h2>Current Theme: {theme}</h2>
    </div>
  );
}

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

  function toggleTheme() {
    setTheme(current =>
      current === 'light' ? 'dark' : 'light'
    );
  }

  return (
    <ThemeContext value={theme}>
      <div>
        <ThemeDisplay />
        <button onClick={toggleTheme}>
          Toggle Theme
        </button>
      </div>
    </ThemeContext>
  );
}

export default App;

How it works

  1. The App component initializes the theme to light.
  2. The Context Provider makes the current theme available to descendants.
  3. ThemeDisplay reads the theme using useContext.
  4. When the button is clicked, the theme changes between light and dark.
  5. React updates the provider value and re-renders components that read the changed context.

This example changes the displayed theme name. You can extend it by applying different CSS classes for the light and dark themes.


8. Complete Example: Theme Context With CSS Classes

This example demonstrates how Context can control the appearance of a simple page.

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

const ThemeContext = createContext('light');

function Content() {
  const theme = useContext(ThemeContext);

  return (
    <main className={`page page-${theme}`}>
      <h2>React Context Example</h2>
      <p>The current theme is {theme}.</p>
    </main>
  );
}

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

  return (
    <ThemeContext value={theme}>
      <div>
        <button
          onClick={() =>
            setTheme(current =>
              current === 'light' ? 'dark' : 'light'
            )
          }
        >
          Switch Theme
        </button>
        <Content />
      </div>
    </ThemeContext>
  );
}

export default App;

CSS styling

.page {
  padding: 20px;
  margin-top: 15px;
  border-radius: 8px;
  transition: background-color 0.2s, color 0.2s;
}

.page-light {
  background-color: #ffffff;
  color: #222222;
}

.page-dark {
  background-color: #222222;
  color: #ffffff;
}

Result: Clicking the button switches the page between the light and dark styles. The Content component does not need to receive the theme through props.


9. Sharing Multiple Values Through Context

A Context value can be a string, number, array, object, or function. You can combine related values into one object when multiple components need access to them.

Example: User Information

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

const UserContext = createContext(null);

function UserDetails() {
  const user = useContext(UserContext);

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Role: {user.role}</p>
    </div>
  );
}

function App() {
  const [user, setUser] = useState({
    name: 'Manish',
    role: 'Student'
  });

  function changeRole() {
    setUser(current => ({
      ...current,
      role: 'Developer'
    }));
  }

  return (
    <UserContext value={user}>
      <UserDetails />
      <button onClick={changeRole}>
        Update Role
      </button>
    </UserContext>
  );
}

export default App;

When the role changes, the user object is replaced with a new object and the provider receives the updated value. Components that read this Context receive the current user data.

Important: Because the default value here is null, this example assumes UserDetails is rendered under the provider. In a production application, consider checking for a missing user value or providing an appropriate fallback.


10. Using Multiple Contexts

An application may need separate Context objects for different types of information. For example, one Context can manage the theme while another manages the current user.

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

const ThemeContext = createContext('light');
const UserContext = createContext('Guest');

function Profile() {
  const theme = useContext(ThemeContext);
  const username = useContext(UserContext);

  return (
    <div>
      <h2>Welcome, {username}!</h2>
      <p>Theme: {theme}</p>
    </div>
  );
}

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

  return (
    <ThemeContext value={theme}>
      <UserContext value="Manish">
        <Profile />
        <button
          onClick={() =>
            setTheme(current =>
              current === 'light' ? 'dark' : 'light'
            )
          }
        >
          Toggle Theme
        </button>
      </UserContext>
    </ThemeContext>
  );
}

export default App;

Profile reads both values independently. When the theme changes, the component receives the new theme value while continuing to access the username through UserContext.


11. Using Context With Functions

Context can provide functions as well as data. This is useful when multiple components need to trigger an action, such as logging in, logging out, or updating shared application settings.

Example: Shared Counter

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

const CounterContext = createContext(null);

function CounterDisplay() {
  const { count } = useContext(CounterContext);

  return <h2>Count: {count}</h2>;
}

function CounterButtons() {
  const { increase, decrease } = useContext(CounterContext);

  return (
    <div>
      <button onClick={decrease}>Decrease</button>
      <button onClick={increase}>Increase</button>
    </div>
  );
}

function App() {
  const [count, setCount] = useState(0);

  const contextValue = {
    count,
    increase: () => setCount(value => value + 1),
    decrease: () => setCount(value => value - 1)
  };

  return (
    <CounterContext value={contextValue}>
      <CounterDisplay />
      <CounterButtons />
    </CounterContext>
  );
}

export default App;

Both child components access the shared counter through Context. CounterDisplay reads the value, while CounterButtons reads the functions that update it.


12. Context Provider and Default Values

The default value is supplied when creating a Context. React uses it only when there is no matching provider above the component that reads the Context.

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 LanguageContext provider above it, it displays English.

Providing a different value

<LanguageContext value="Hindi">
  <LanguageDisplay />
</LanguageContext>

Now LanguageDisplay receives Hindi instead of the default value.

Important: If a matching provider exists but its value is explicitly undefined, useContext returns undefined rather than falling back to the default value.


13. Nested Context Providers

You can place one provider inside another provider for the same Context. A component reads the value from the closest matching provider above it.

import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemeLabel() {
  const theme = useContext(ThemeContext);

  return <p>Theme: {theme}</p>;
}

function App() {
  return (
    <ThemeContext value="dark">
      <ThemeLabel />
      <ThemeContext value="light">
        <ThemeLabel />
      </ThemeContext>
    </ThemeContext>
  );
}

export default App;

The first ThemeLabel reads dark, while the nested ThemeLabel reads light. The inner provider overrides the outer value for its descendants only.


14. Rules of the useContext Hook

  • Call useContext at the top level of a function component or custom Hook.
  • Do not call useContext inside loops, conditions, or nested functions.
  • Create Context using createContext() outside your components.
  • Place the matching provider above the components that need the value.
  • Use the same Context object when providing and reading its value.
  • Remember that useContext reads the nearest matching provider above the component.
  • Changing the provider value causes components that read the changed Context to re-render.
  • Use the value prop to pass data to the provider.
  • Use state or another suitable source to update dynamic Context values.
  • Do not use Context automatically for every piece of application data; choose the simplest suitable data-sharing approach.

15. Common Mistakes When Using useContext

Mistake Why It Is a Problem Correct Approach
Forgetting the provider The component receives the Context default value. Wrap the component in the matching provider when a custom value is required.
Using the wrong Context object The component may read a different Context from the one being provided. Import and use the same exported Context object.
Using the wrong provider prop Passing theme={theme} instead of value={theme} does not provide the intended value. Use the provider's value prop.
Calling useContext conditionally Violates the Rules of Hooks. Call useContext at the top level.
Expecting default value to update The default value is static and is only a fallback. Store changing values in state and pass them through a provider.
Putting too much unrelated data in one Context Changes may cause more components to update than necessary. Consider separate Contexts for independent data.
Creating a new object value on every render The new object reference can cause Context consumers to re-render. When needed, consider useMemo and useCallback to stabilize values and functions.

16. Performance Considerations

When a provider receives a different Context value, React re-renders components that read that Context. React compares the previous and next values using Object.is.

For example, passing a new object on every render creates a different reference, even if its properties are unchanged.

Example of an object value

<UserContext value={{ name: 'Manish', role: 'Student' }}>
  <Profile />
</UserContext>

In this example, a new object is created whenever the containing component renders. If this causes unnecessary updates in a larger application, you can consider using useMemo to preserve the object reference when its dependencies have not changed.

Using useMemo for a Context value

import { createContext, useMemo, useState } from 'react';

const UserContext = createContext(null);

function App() {
  const [name, setName] = useState('Manish');
  const [role, setRole] = useState('Student');

  const user = useMemo(() => ({
    name,
    role
  }), [name, role]);

  return (
    <UserContext value={user}>
      {/* Context consumers go here */}
    </UserContext>
  );
}

This optimization keeps the object reference stable while name and role remain unchanged. useMemo is a performance optimization, not a requirement for every Context provider.


17. useContext vs Props

Feature Props Context
Data flow Explicitly passed from parent to child. Made available to descendant components through a provider.
Best for Direct parent-child communication. Sharing values across many levels of a component tree.
Intermediate components May need to forward props. Do not need to forward the Context value.
Complexity Simple for a small component tree. Useful when many descendants need the same information.
Common examples Button labels, card titles, individual item data. Theme, locale, current user, shared settings.

18. useContext vs useState

Feature useContext useState
Main purpose Reads a value provided by a matching Context provider. Stores and updates local component state.
Creates state by itself No. Yes.
Shares data across descendants Yes, when combined with a provider. Not automatically; the state must be passed through props or Context.
Typical use Reading shared theme or user information. Managing a counter, input value, or open/closed state.
Can be combined Yes, to read state shared through Context. Yes, to hold the state supplied by a Context provider.

19. Practical Project: User Profile With Context

Build a small application that shares user information across components and allows the displayed role to change.

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

const UserContext = createContext(null);

function UserProfile() {
  const user = useContext(UserContext);

  return (
    <section>
      <h2>User Profile</h2>
      <p>Name: {user.name}</p>
      <p>Role: {user.role}</p>
    </section>
  );
}

function App() {
  const [user, setUser] = useState({
    name: 'Manish',
    role: 'Student'
  });

  function promoteUser() {
    setUser(current => ({
      ...current,
      role: 'React Developer'
    }));
  }

  return (
    <UserContext value={user}>
      <UserProfile />
      <button onClick={promoteUser}>
        Update Role
      </button>
    </UserContext>
  );
}

export default App;

Project features

  • Shares user data using Context.
  • Reads the user information with useContext.
  • Stores the user object in useState.
  • Updates the role without mutating the existing user object.
  • Automatically updates the profile when the provider value changes.

Additional practice tasks

  1. Add a theme toggle using ThemeContext.
  2. Create a language selector using LanguageContext.
  3. Share cart items between a product list and cart summary.
  4. Create a login/logout example using AuthContext.
  5. Split unrelated shared values into separate Context objects.

20. Interview Questions and Answers

Q1. What is useContext in React?

Answer: useContext is a React Hook that reads and subscribes to a Context value provided by the nearest matching provider above a component.

Q2. What is prop drilling?

Answer: Prop drilling is passing data through intermediate components that do not need the data themselves so that a deeper component can receive it.

Q3. What is createContext?

Answer: createContext creates a Context object that can be used to provide and read a shared value.

Q4. What happens when a component has no matching provider?

Answer: useContext returns the default value supplied to createContext.

Q5. Can Context values change?

Answer: Yes. A provider can receive a changing value, often from useState or useReducer. Components reading the changed Context are updated by React.

Q6. Does useContext create state?

Answer: No. It reads a Context value. State can be created separately and passed through the provider.

Q7. Can we use multiple Contexts in one component?

Answer: Yes. A component can call useContext for multiple Context objects at the top level.

Q8. What is the difference between props and Context?

Answer: Props explicitly pass data between components, while Context allows descendant components to read a shared value without forwarding it through every intermediate component.

Q9. Does changing Context cause re-renders?

Answer: React re-renders components that read a Context when the provider value changes according to Object.is comparison.

Q10. Can Context provide functions?

Answer: Yes. Context can provide functions alongside data, such as login, logout, or shared state-update functions.

Q11. Can useContext be called inside an if statement?

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

Q12. What is the difference between createContext and useContext?

Answer: createContext creates the Context object. useContext reads the value from the nearest matching provider above the component.


21. Practice Exercises

  1. Create a ThemeContext and switch the page between light and dark themes.
  2. Create a UserContext that displays a user's name and role in different components.
  3. Build a language selector and share the selected language with a nested component.
  4. Create a shopping cart Context that shares the cart item count between a header and product page.
  5. Build a login/logout example using Context and state.
  6. Demonstrate prop drilling and then refactor the example to use Context.
  7. Create two nested providers for the same Context and explain which value each child receives.
  8. Identify a Context value that changes unnecessarily because a new object is created on every render.

22. Quick Revision Checklist

  • Understand the purpose of useContext.
  • Know how createContext creates a Context object.
  • Understand how providers supply values to descendants.
  • Know how to read Context using useContext.
  • Understand prop drilling and how Context can reduce it.
  • Know how to share changing values using useState and Context.
  • Understand default values and nested providers.
  • Learn how to use multiple Contexts.
  • Understand why Context changes can trigger re-renders.
  • Follow the Rules of Hooks and use Context only where it helps.

23. Official React Documentation


24. Conclusion

The useContext Hook is an important React feature for sharing information across components without passing props through every intermediate level. By combining createContext, a Context Provider, useContext, and state, developers can build reusable and maintainable features such as themes, user profiles, language settings, and shopping carts.

Remember: createContext creates the Context, the provider supplies its value, and useContext reads that value from the nearest matching provider above the component.

Explore JustAcademy React JS Training and Register for React JS Course Demo to continue learning React JS concepts and practical development.

Previous Next
whatsapp