createContext
- React Native course
- Intermediate
- Lesson 14/116
- 5 min
Learn to create a context with createContext.
What is createContext?
createContext is a function that creates a new context object. When you write const ThemeContext = createContext(defaultValue) it returns a context; this object has a Provider property. The default value is used when no Provider is found.
To import it you write import { createContext } from "react". A context is usually defined in its own file; both providing and consuming components import from the same source. The context name starts with a capital letter (for example ThemeContext); this avoids confusion with component names. The object returned by createContext is stable; it stays the same on every render.
The default value
The first argument passed to createContext is the default value. When you write createContext("light"), if a component is not inside any Provider, useContext returns this value.
The default value is often left as null or undefined; this way a developer who forgets the Provider notices it at once. Sometimes a real value is given: for example a "light" theme or a "tr" locale. This value is used only when no Provider exists; if a Provider exists, its value takes priority.
Practice Call createContext
Create a context named LocaleContext. With createContext give the default value "tr". Then log it with console.log(LocaleContext).
Starter code
// Import createContext
// Create LocaleContext with createContext; default "tr"
// Log LocaleContextSample solution
import { createContext } from "react";
const LocaleContext = createContext("tr");
console.log(LocaleContext);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Create the context
const ThemeContext = ____("light");
const ThemeContext = createContext("light");
Explanation: The createContext call creates the context.
2 What does createContext return?
const ThemeContext = createContext("light");- A component
- An object containing a Provider Correct answer
- Bir dizi
- A number
Explanation: createContext returns an object with a Provider.
3 Match each piece to its role
| Term | Meaning |
|---|---|
createContext |
Creates the context |
Provider |
Provides the value |
default |
Used without Provider |
useContext |
Reads the value |