OnlineCBT Logo OnlineCBT
React Tutorial
REACT · LESSON 10

Global State Management with useContext Hook

By Ratan Updated: 16 Oct 2026

Pass data deep down component trees without prop-drilling using React Context API and useContext.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. The Problem of "Prop Drilling"

In standard React, data is passed down top-to-bottom via props. When deep components (e.g. 5 levels down) need access to user credentials or theme settings, you are forced to pass props through intermediate components that don't even need the data. This anti-pattern is known as Prop Drilling.

2. The React Context API Solution

Context provides a way to pass data through the component tree without manually passing props at every level. It consists of three parts:

  1. createContext() – Creates the context container.
  2. – Supplies the shared data to all children.
  3. useContext(Context) – Consumes the shared data anywhere inside child components.

3. Building an Authentication Context

// AuthContext.jsx
import { createContext, useContext, useState } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState({ name: "Admin", role: "SuperAdmin" });

  const login = (userData) => setUser(userData);
  const logout = () => setUser(null);

  return (
    
      {children}
    
  );
}

// Custom convenience hook for consuming AuthContext
export const useAuth = () => useContext(AuthContext);

4. Consuming Context in Deep Components

// UserProfileWidget.jsx
import { useAuth } from './AuthContext';

function UserProfileWidget() {
  const { user, logout } = useAuth();

  if (!user) return ;

  return (
    
Logged in as: {user.name} ({user.role})
); }

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat