CodeBlanks Logo Icon CodeBlanks

createContext

Learn to create a context with createContext and a default value.

createContext

The createContext(defaultValue) call returns a context object. This object holds two parts: Provider (the value-giving side) and Consumer/reading side.

The default value is used only when there's no Provider above in the tree. So if no Provider wraps the component, it reads defaultValue; if wrapped, it reads the Provider's value.

The context object name must start with a capital letter; this is how React tells components from contexts. Like ThemeContext, UserContext.

Parts of the context object

Every context object has two important parts: Provider and the reading hook useContext. Provider is used like a component and takes a value prop.

You put the Provider somewhere high in the tree; all components inside can read the value. Multiple Providers can nest; the innermost wins.

On the reading side, the useContext(MyContext) call returns the value of the nearest Provider. We'll cover this hook in detail in the next lesson.

Practice Create UserContext

Complete the skeleton. Create a context called UserContext; pass null as the default value to createContext. Export the result.

Starter code

App.jsx
// Define UserContext here
import { createContext } from "react";

Sample solution

App.jsx
import { createContext } from "react";

const UserContext = createContext(null);

export default UserContext;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the default value used?

  • When there is a Provider
  • Never
  • Always
  • When there is no Provider Correct answer

Explanation: The default is used only without a Provider.

2 Context naming

Question
The context object name starts with a ____ letter.
Answer
The context object name starts with a capital letter.

Explanation: Context names start with a capital letter.

3 Match the context parts

Term Meaning
Provider Gives value
value Data prop
useContext Reading hook
defaultValue No Provider

All lessons in Beginner