Course contentsShow
← React
Lesson 788 of 2,39621. Context FundamentalsFree lesson

Creating a Context with createContext

Using React.createContext() to initialize a new context object with an optional default value.

Creating a Context with createContext

What you'll learn: How to initialize a new Context object using React.createContext() so you can share data across your component tree without prop drilling.

The Core Idea

Now that you understand why Context exists (avoiding prop drilling for global-ish data), let's actually create one. React gives you a function called createContext() that manufactures a brand new Context object. Think of it like ordering a custom postal service for your component tree—you're setting up the infrastructure before you start sending messages.

When you call createContext(), you can optionally provide a default value. This default is what components will "see" if they try to consume the Context but aren't wrapped in a Provider (we'll cover Providers in the next lesson). It's like a fallback—a safety net.

The Syntax

import { createContext } from 'react';

// Without a default value
const MyContext = createContext();

// With a default value
const ThemeContext = createContext('light');

// With a complex default value
const UserContext = createContext({
  name: 'Guest',
  isAuthenticated: false
});

The variable you assign (MyContext, ThemeContext, UserContext) becomes your "channel" for broadcasting and receiving data. You'll use this object in two ways later: to provide values (.Provider) and to consume values (via hooks).

When the Default Value Matters

If you render a component that consumes ThemeContext but it's not wrapped in a ThemeContext.Provider, it'll receive 'light' as the theme. In practice, you usually will have a Provider, so the default often serves as documentation or a TypeScript hint rather than a real runtime value.

Key Takeaway: createContext() initializes a new Context object with an optional default value, creating the infrastructure to share data across your component tree without manual prop passing.