useContext

what is useContext() ?

  • Profile picture of Mcs
  • by Mcs July 2, 2025

useContext() is a React Hook that enables functional components to subscribe to and read context values. It provides a way to access data that is shared across the component tree without the need for "prop drilling," which involves passing props down manually through multiple levels of nested components.

useContext() is a React Hook that allows you to use global/shared data (context) in any function component — without passing props manually at every level.

Why useContext()?

In React, if you want to pass data from a parent to deeply nested child components, you'd usually have to pass props down through every level.

useContext() + Context API solves this by sharing data globally across components.

Steps to Use useContext()

1. Create a Context

import { createContext } from 'react';

const ThemeContext = createContext(); // create context

2. Provide Context Value

Wrap a part of your app with the Provider and give it a value.

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

3. Use the Context Value

Now any child component can access that context using useContext():

import { useContext } from 'react';

function Header() {
 const theme = useContext(ThemeContext); // read context value
 return <h1 className={theme}>Welcome</h1>;
}

Full Working Example

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

// Step 1: Create
const UserContext = createContext();

// Step 2: Provide
function App() {
 const user = { name: 'Jigar', role: 'Developer' };

 return (
   <UserContext.Provider value={user}>
     <Profile />
   </UserContext.Provider>
 );
}

// Step 3: Use in any child
function Profile() {
 const user = useContext(UserContext);
 return <h2>Hello, {user.name} - {user.role}</h2>;
}

Summary

FeatureDescription
createContext()Creates a context to share data
.ProviderProvides the context value
useContext()Consumes the context value in component
BenefitAvoids "prop drilling" in deep trees

When to Use useContext()

  1. Theme switcher (light/dark mode)
  2. Auth or User info (logged in user data)
  3. Language/localization
  4. App-wide settings

 

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.