Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 10 of the Intermediate React: Hooks, State & Data Patterns course
ReactJune 25, 20263 min read

Introduction to Context API: Avoiding Prop Drilling in React

Learn how to use the Context API and useContext to share data across your React application, effectively eliminating prop drilling for cleaner code.

ReactHooksContext APIState ManagementFrontend Architecturejavascriptfrontend

Previously in this course, we explored managing complex object-based state using useReducer. While that handles state transitions beautifully, we still face the challenge of getting that state into the components that actually need it.

In larger applications, passing data through every level of your component tree—a pattern known as prop drilling—becomes a maintenance nightmare. Today, we’ll solve this using the context API. This tool allows you to broadcast data to your component tree, letting any component "subscribe" to it directly, regardless of its depth.

The Problem: Why Prop Drilling Hurts

Imagine your dashboard project. You have a User object that needs to be accessed by the Navbar, the ProfileSettings page, and the Sidebar. If you store this in your top-level App component, you have to pass that user prop through layers of intermediate components that don't even use the data.

This creates "middleman" components that are harder to test and reuse, as they are burdened with props they don't care about. The context API provides a way to share these values without explicit passing at every level.

Implementing Context from First Principles

To use context, we follow a three-step pattern:

  1. Create the Context: Define the "pipe" for your data.
  2. Provide the Context: Wrap your component tree with a Provider to set the value.
  3. Consume the Context: Use the useContext hook to access the data.

1. Creating the Context

First, create a new file, UserContext.js. We use createContext to initialize our storage.

JAVASCRIPT
import { createContext } from CE9178">'react';

// You can provide a default value here, usually null or an empty object
export const UserContext = createContext(null);

2. Implementing the Provider

The Provider is a component that accepts a value prop. Any component inside this provider can access that value. In our dashboard, we’ll wrap our main layout.

JAVASCRIPT
import { UserContext } from CE9178">'./UserContext';

function App() {
  const user = { name: CE9178">'Alex', role: CE9178">'Admin' };

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

3. Consuming with useContext

Now, any child component can grab the user data without props.

JAVASCRIPT
import { useContext } from CE9178">'react';
import { UserContext } from CE9178">'./UserContext';

function Navbar() {
  const user = useContext(UserContext);
  return <nav>Welcome, {user.name}</nav>;
}

Hands-on Exercise: Dashboard User Context

In our running dashboard project, let's inject the current user's theme preference.

  1. Create a ThemeContext.js file using createContext('light').
  2. In your App.js, wrap your main dashboard component with <ThemeContext.Provider value="dark">.
  3. Create a ThemeButton component that uses useContext(ThemeContext) to display the current theme string.
  4. Place ThemeButton deep inside your dashboard hierarchy (e.g., inside a SettingsPanel inside Dashboard) and verify it receives the value without passing it as a prop.

Common Pitfalls to Avoid

  • Over-using Context: Context is not a replacement for all prop passing. If you only pass data one or two levels down, props are often cleaner and easier to track. Use context for truly global data like themes, auth status, or user settings.
  • Performance Issues: Every time the value passed to a Provider changes, all components consuming that context will re-render. We will cover how to optimize this in later lessons, but for now, keep your context values stable.
  • Missing Providers: If you try to consume a context outside of its Provider, you will get the default value you passed to createContext. Always ensure your Provider is high enough in the tree.

Recap

The context API is your primary tool for avoiding prop drilling in React. By using createContext, the Provider component, and the useContext hook, you can build a more decoupled component architecture. While it’s powerful for global state, use it judiciously to keep your application performant and easy to debug.

Up next: We’ll look at Architecting Global State with Context and Reducer to create a robust, centralized store for our dashboard.

Previous lessonManaging Object-Based StateNext lesson Architecting Global State with Context and Reducer
Back to Blog

Similar Posts

ReactJune 25, 20263 min read

Integrating Reducers with Auth State: A Robust Pattern

Master authentication state management by integrating useReducer. Learn to handle loading, errors, and token logic for a secure, predictable React flow.

Read more
ReactJune 25, 20263 min read

Structuring State for Performance: Optimizing React Context

Stop React performance bottlenecks caused by the Context API. Learn how to split contexts, memoize values, and prevent unnecessary re-renders in your app.

Part of the course

Intermediate React: Hooks, State & Data Patterns

intermediate · Lesson 10 of 48

  1. 1

    Mastering useRef for DOM Access

    4 min
  2. 2

    Persistent Mutable Values with useRef

    4 min
  3. 3

    Memoizing Expensive Calculations with useMemo

    3 min
Read more
ReactJune 25, 20264 min read

Implementing Theme Context: A Global Toggle for React Dashboards

Learn to build a production-ready theme system using the Context API and useReducer. Master global state for light/dark mode in your React dashboard.

Read more
4

Optimizing Function References with useCallback

3 min
  • 5

    Introduction to Custom Hooks

    4 min
  • 6

    Building a useLocalStorage Hook

    4 min
  • 7

    Refactoring Dashboard Settings

    4 min
  • 8

    Complex State with useReducer

    3 min
  • 9

    Managing Object-Based State

    3 min
  • 10

    Introduction to Context API

    3 min
  • 11

    Architecting Global State with Context and Reducer

    3 min
  • 12

    Implementing Theme Context

    4 min
  • 13

    Structuring State for Performance

    3 min
  • 14

    Handling Authentication State

    3 min
  • 15

    Integrating Reducers with Auth State

    3 min
  • 16

    Introduction to React Router

    3 min
  • 17

    Dynamic Routing with URL Parameters

    Coming soon
  • 18

    Nested Routes and Layouts

    Coming soon
  • 19

    Protected Routes for Authenticated Views

    Coming soon
  • 20

    Programmatic Navigation

    Coming soon
  • 21

    Building the Dashboard Navigation Structure

    Coming soon
  • 22

    Asynchronous Data Lifecycle

    Coming soon
  • 23

    Caching Strategies with React Query

    Coming soon
  • 24

    Mutations and Data Updates

    Coming soon
  • 25

    Synchronizing Client and Server State

    Coming soon
  • 26

    Integrating Live Data into the Dashboard

    Coming soon
  • 27

    Error Handling and Loading UI

    Coming soon
  • 28

    Controlled vs Uncontrolled Components

    Coming soon
  • 29

    Real-time Form Validation

    Coming soon
  • 30

    Schema-based Validation with Zod

    Coming soon
  • 31

    Handling Multi-step Forms

    Coming soon
  • 32

    Optimizing Form Submissions

    Coming soon
  • 33

    Performance Profiling with React DevTools

    Coming soon
  • 34

    Refactoring for Scalability

    Coming soon
  • 35

    Finalizing Dashboard Data Flow

    Coming soon
  • 36

    Deploying the Application

    Coming soon
  • 37

    Advanced Hook Composition

    Coming soon
  • 38

    Implementing Middleware for State

    Coming soon
  • 39

    Advanced Context Patterns

    Coming soon
  • 40

    Router Loaders and Data Prefetching

    Coming soon
  • 41

    Complex Route Guards

    Coming soon
  • 42

    Handling Large Datasets in UI

    Coming soon
  • 43

    Testing Hooks and Components

    Coming soon
  • 44

    Managing Global Modals

    Coming soon
  • 45

    Implementing Keyboard Shortcuts

    Coming soon
  • 46

    Optimizing Asset Loading

    Coming soon
  • 47

    Internationalization Basics

    Coming soon
  • 48

    Managing WebSocket Connections

    Coming soon
  • View full course