Hello! Welcome back to our module on Advanced State, Context, and Refs.
In our previous lesson, we thoroughly explored the problem of "prop drilling" and understood why it can make large React applications difficult to maintain and refactor. We concluded that while passing props is fine for shallow component trees, we need a better solution for sharing state across distant components.
Today, we'll learn about that solution: React's Context API. Our goal is to create and provide global state using React.createContext with TypeScript. We'll focus on the first half of the equation: setting up the "supply line" for our data. You'll learn how to create a context, type it correctly, and then use a Provider to make a value available to a part of your application's component tree.
1. What is React Context? A High-Level View
The Context API is React's built-in mechanism for solving prop drilling. It allows you to create a "global" state for a set of components, enabling a parent to make data available to any component in the tree below it, regardless of how deeply nested that component is.
You can think of it as a data "teleporter." Instead of passing data manually down through every level, you place it in a special Provider at the top of a tree. Then, any component inside that tree can "subscribe" directly to that data.

The Context API consists of two main parts:
- The Context Object: Created with
React.createContext(). This object acts as the channel or conduit for your data. - The Provider: A component, available on the context object (e.g.,
MyContext.Provider), that accepts avalueprop. It's responsible for making this value accessible to all its descendant components.
Today, we're focusing on creating the context object and its provider. In the next lesson, we'll cover how to consume the value.
2. Step 1: Creating a Context
The first step is to create a context object using the React.createContext() function. A common practice is to create a dedicated file for your context to keep your code organized.
Let's imagine we want to manage a theme (e.g., 'light' or 'dark' mode) for our application. We could start by creating src/context/ThemeContext.ts.
// src/context/ThemeContext.ts
import React from 'react';
const ThemeContext = React.createContext(); // What goes in here?
React.createContext() accepts an optional defaultValue. This value is used only when a component tries to consume the context without having a matching Provider above it in the tree.
While you might be tempted to provide a default object like { theme: 'light' } to avoid errors, it's often better not to. A context is rarely useful without a real, stateful Provider. Providing a static default can mask bugs where you've forgotten to wrap a component in the provider. A better approach is to let the app fail loudly so you can fix the issue.
How to use React Context effectively
For a deeper dive into this philosophy, I recommend reading Kent C. Dodds's excellent article, "How to use React Context effectively." He makes a strong case for why omitting the default value is often the right choice.
Read the first section of the article, down to where it says "The Custom Provider Component." Focus on the argument for not providing an initial value and why it leads to more robust code, even if it seems counter-intuitive at first.
Following this advice, we'll intentionally provide undefined as the default value. This brings us to the next crucial step: typing.
3. Step 2: Typing the Context with TypeScript
Since you're proficient in TypeScript, you know how important it is to define the "shape" of our data. With context, we use a generic to specify the type of the value the context will hold.
Because we are creating the context outside of a React component, it doesn't have access to any state yet. This is why we initialize it with undefined. Consequently, our context's type must reflect that it can be either our desired context type or undefined.
Learn React Hooks: useContext - Simply Explained!
This video from Cosden Solutions clearly explains this exact scenario. It demonstrates creating a context for user data and shows why the type must accommodate the initial undefined value.
Watch the segment from 04:03 to 06:32. Pay close attention to how createContext is typed using <User | undefined> and the explanation for why this is necessary.
Let's apply this to our theme example. We need to define the shape of our context value, which will include the current theme and a function to change it.
// src/context/ThemeContext.ts
import React from 'react';
// 1. Define the shape of the context's value
export type Theme = 'light' | 'dark';
export interface ThemeContextType {
theme: Theme;
toggleTheme: () => void;
}
// 2. Create the context with a type and a default value of undefined
export const ThemeContext = React.createContext<ThemeContextType | undefined>(undefined);
By defining ThemeContextType, we've created a contract. Any provider for this context must supply a value that matches this interface, and any consumer can trust that it will receive an object of this shape (or undefined, which we'll handle later).
4. Step 3: Providing the Context Value
Creating the context gives us the "channel," but it doesn't provide any data. To do that, we use the Provider component that comes with our context object.
The Provider component is used to wrap a part of your component tree. It has a mandatory value prop, which is where you pass the data you want to make available.
Learn React Hooks: useContext - Simply Explained!
The same video from Cosden Solutions continues to show exactly how to use the provider to wrap components and pass the value.
Now watch from 06:32 to 07:42. The video shows how DashboardContext.Provider is used to wrap the Dashboard component and how the user state is passed into its value prop.
5. The Custom Provider Component Pattern
While you can use <ThemeContext.Provider> directly in your App.tsx, a much more robust and common pattern is to create a custom Provider Component. This component encapsulates the state management logic (useState, in our case) and wraps its children with the actual Context.Provider.
This has several benefits:
- Encapsulation: The state logic for the theme is contained within
ThemeProvider. - Reusability: You can easily wrap any part of your app with
ThemeProvider. - Cleanliness: Your
Appcomponent doesn't get cluttered with state logic that's only for the theme.
Let's build a ThemeProvider component. It's common to place this in a .tsx file, as it's a React component.
// src/context/ThemeProvider.tsx
import React, { useState } from 'react';
import { ThemeContext, ThemeContextType, Theme } from './ThemeContext';
// Define the props for our provider component
interface ThemeProviderProps {
children: React.ReactNode;
}
export const ThemeProvider = ({ children }: ThemeProviderProps) => {
// The state that will be shared
const [theme, setTheme] = useState<Theme>('light');
// The function to update the state
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
// The value that will be passed to the provider
const value: ThemeContextType = {
theme,
toggleTheme,
};
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
};
Now, to make the theme available to our entire application, we simply wrap our root component (or the relevant part of the tree) in main.tsx or App.tsx.
// src/App.tsx
import { ThemeProvider } from './context/ThemeProvider';
import SomePageComponent from './SomePageComponent';
function App() {
return (
<ThemeProvider>
{/*
Every component rendered inside ThemeProvider,
no matter how deep, can now access the theme and toggleTheme function.
*/}
<SomePageComponent />
</ThemeProvider>
);
}
export default App;
We have now successfully created a global state provider!
Test your understanding!
Imagine you're building a feature for user authentication. You need a context to provide the current user's information (or null if not logged in) and a function to log in.
Define the TypeScript types and create the AuthContext object. What would AuthContextType look like? How would you call React.createContext?
Show answer
Here's one possible solution:
import React from 'react';
// A simple user object type
interface User {
id: string;
name: string;
email: string;
}
// The shape of the context value
interface AuthContextType {
user: User | null;
login: (userData: User) => void;
logout: () => void;
}
// Create the context, typed and initialized with undefined
const AuthContext = React.createContext<AuthContextType | undefined>(undefined);
Next, you would create an AuthProvider component that uses useState to manage the user object and provides the user, login, and logout functions in its value prop.
Conclusion
In this lesson, we took the first major step toward solving prop drilling. You learned how to create a global state mechanism using the React Context API.
Key Takeaways:
React.createContext()is used to create a context object that acts as a channel for shared data.- It's a best practice to initialize the context with
undefinedand define its type as<YourType | undefined>to catch components used outside aProvider. - The
<Context.Provider>component is used to inject avalueinto the component tree. - The Custom Provider Pattern (e.g.,
ThemeProvider) is the standard way to encapsulate state logic and provide context to your application, making your code cleaner and more maintainable.
Preview of the Next Lesson:
We've successfully set up the "supply" side of our global state. But how do components access this data? In the next lesson, we will learn how to consume context in nested components using the useContext hook. This will complete the picture and give you a powerful tool for managing state in any React application.