Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 43

Using `useContext` in Nested Components

Recommended resources

Hello! Welcome back to our lesson on advanced state management in React.

In our last session, we tackled the first part of the React Context puzzle. We learned how to identify prop drilling, create a Context object with React.createContext, and build a custom Provider component (like ThemeProvider) to supply a value to a part of our component tree. We set up the "supply line" for our shared state.

Today, we'll complete the picture. Our goal is to consume context in nested components using the useContext hook. You'll learn how to "tap into" the supply line from any component within the provider's scope, finally solving the prop drilling problem and enabling elegant, decoupled state sharing.

1. The useContext Hook: Accessing Shared Data

Now that we have a ThemeProvider wrapping our application, how do our components actually get the theme and toggleTheme function? This is where the useContext hook comes in.

The useContext hook is a function that accepts a context object (the one we created with React.createContext) and returns that context's current value. The value it returns is determined by the value prop of the nearest Provider for that context, up in the component tree.

The syntax is straightforward:

import { useContext } from 'react';
import { ThemeContext } from './ThemeContext'; // The context object we created

const MyComponent = () => {
  const contextValue = useContext(ThemeContext);
  // ... use contextValue
};

Let's see this in a practical example.

Learn React Hooks: useContext - Simply Explained!

To start, let's watch a clear demonstration of useContext in action. This video from Cosden Solutions shows how child components can directly access data provided by a context, bypassing intermediate components.

Watch the segment from 07:42 to 08:59. Notice how the Sidebar and Profile components use useContext(DashboardContext) to get the user data directly, eliminating the need for props.

As you saw, useContext makes consuming data incredibly simple. However, if you've been following along with our ThemeContext example, you might spot a TypeScript-related issue.


2. The undefined Problem and a Robust Solution

In the last lesson, we intentionally typed our context as ThemeContextType | undefined and created it with React.createContext<ThemeContextType | undefined>(undefined). This was a deliberate choice to help us catch bugs where we might forget to wrap a component in a ThemeProvider.

Now, when we consume it, TypeScript correctly infers this type:

import { useContext } from 'react';
import { ThemeContext } from './context/ThemeContext';

const ThemedButton = () => {
  // `themeContext` has the type: ThemeContextType | undefined
  const themeContext = useContext(ThemeContext);

  // This would cause a TypeScript error! 'themeContext' could be undefined.
  // const { theme, toggleTheme } = themeContext;

  // We would have to do this in every component:
  if (!themeContext) {
    // What do we do here? Render nothing? Throw an error?
    return null;
  }

  const { theme, toggleTheme } = themeContext;

  return <button onClick={toggleTheme}>Current Theme: {theme}</button>;
};

Adding this if check in every single component that consumes the context is repetitive and clutters our component logic. More importantly, if the context is undefined, it likely indicates a developer error (a missing provider), and we want our application to fail fast and loudly in development.

This is where a powerful and widely-used pattern comes into play: the custom consumer hook.

Instead of exporting our ThemeContext object and having components use useContext(ThemeContext) directly, we will create and export a custom hook, let's call it useTheme(). This hook will do three things for us:

  1. Call useContext(ThemeContext) internally.
  2. Check if the returned value is undefined.
  3. If it is, throw a descriptive error.
  4. If it's not, return the value, which TypeScript now knows is of type ThemeContextType.

This encapsulates the logic for consuming the context, provides a better developer experience, and ensures type safety.

Learn React Hooks: useContext - Simply Explained!

The same video from Cosden Solutions perfectly illustrates this exact pattern. It explains the problem with the undefined type and walks through creating a custom hook to solve it.

Watch from 08:59 to 14:50. This is the most crucial part of today's lesson. Pay close attention to how the useUserContext custom hook is created. It performs a runtime check and throws an error, which in turn allows the component using the hook to safely access the user object without optional chaining or type guards.

This pattern is considered a best practice by many in the React community, including prominent developers and the official React documentation.

How to use React Context effectively

To reinforce this concept, let's look at two excellent written resources that advocate for the same pattern. First, Kent C. Dodds's blog post, which you saw in the last lesson, also covers creating a custom consumer hook.

Read the section titled "The Custom Consumer Hook". It demonstrates the exact same pattern of creating a useCount hook that wraps useContext and includes the runtime check.

Using TypeScript

The official React documentation also recommends this approach when dealing with potentially null or undefined context values.

Read the section under the useContext heading. Focus on the second code block and the accompanying explanation. It shows how a useGetComplexObject hook checks for a null context and throws an error, thereby removing the | null from the type for consumers.


3. Implementing Our Custom useTheme Hook

Let's apply this pattern to our ThemeContext. We can add the custom hook directly into our ThemeContext.ts file or create a separate file for it. For simplicity, let's add it to ThemeContext.ts.

// src/context/ThemeContext.ts
import React, { createContext, useContext } from 'react';

// Types from the previous lesson
export type Theme = 'light' | 'dark';
export interface ThemeContextType {
  theme: Theme;
  toggleTheme: () => void;
}

// Create the context
export const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// The custom hook!
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

Now, let's refactor our ThemedButton component to use this new hook. Notice how much cleaner and safer it becomes.

// src/components/ThemedButton.tsx
import { useTheme } from '../context/ThemeContext'; // Import the custom hook

const ThemedButton = () => {
  // `theme` and `toggleTheme` are guaranteed to exist here.
  // The type is correctly inferred as ThemeContextType.
  const { theme, toggleTheme } = useTheme();

  const buttonStyle = {
    backgroundColor: theme === 'light' ? '#FFF' : '#333',
    color: theme === 'light' ? '#000' : '#FFF',
    padding: '10px 20px',
    border: '1px solid',
    borderRadius: '5px',
    cursor: 'pointer'
  };

  return (
    <button style={buttonStyle} onClick={toggleTheme}>
      Toggle to {theme === 'light' ? 'Dark' : 'Light'} Mode
    </button>
  );
};

export default ThemedButton;

With useTheme, our component code is clean. It simply asks for the theme data and uses it. The boilerplate and safety checks are encapsulated within the hook itself. If a developer forgets to add <ThemeProvider> in the component tree, they'll get a clear, immediate error in development, pointing them straight to the problem.

Test your understanding!

In the last lesson, you designed the types for an AuthContext. The context type was AuthContextType | undefined.

interface User {
  id: string;
  name: string;
  email: string;
}

interface AuthContextType {
  user: User | null;
  login: (userData: User) => void;
  logout: () => void;
}

const AuthContext = React.createContext<AuthContextType | undefined>(undefined);

Your task: Write the useAuth custom hook that consumes this context. It should follow the pattern we've just learned, ensuring it throws an error if used outside of an AuthProvider.

Show answer

Here is the implementation of the useAuth custom hook:

import { useContext } from 'react';

// Assume AuthContext is imported from its file

export const useAuth = () => {
  const context = useContext(AuthContext);
  
  // The crucial check
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  
  // Return the context value, now guaranteed to be of type AuthContextType
  return context;
};

Any component can now call const { user, login, logout } = useAuth(); and get a type-safe, guaranteed-to-exist context value.


Conclusion

Congratulations! You've now mastered the full lifecycle of React's Context API, from providing state to consuming it in a robust, type-safe manner.

Key Takeaways:

  • The useContext hook is the standard way to read a context's value within a functional component.
  • When a context is created with a default value of undefined, consumers will receive a type of YourType | undefined.
  • The best practice to handle this is to create a custom consumer hook (e.g., useTheme).
  • This custom hook wraps the useContext call, performs a runtime check for undefined, and throws a descriptive error if the provider is missing.
  • This pattern leads to cleaner component code, improved type safety, and a better developer experience with clearer error messages.

Preview of the Next Lesson:

Our ThemeProvider currently uses useState to manage its state. This works perfectly well for simple state like a theme string. But what if the state logic becomes more complex, with multiple interconnected actions? In our next lesson, we will introduce the useReducer hook for managing complex state transitions. This will provide us with a more scalable and predictable way to handle state, which we can then combine with the Context API for truly powerful state management solutions.