What is Context?
- React Native course
- Intermediate
- Lesson 13/116
- 5 min
Learn global state with the Context API.
What is Context?
In React Native Context lets you share data through the component tree without manually passing props. A parent provides a value; descendants read it directly. This solves prop drilling (passing the same prop at every layer).
For example theme, user session or locale are used across the whole app. Context keeps them in one source. Context is ideal for global data like theme and locale; use it carefully for frequently changing values due to performance concerns. It is set up in three steps: create, provide, consume.
Three steps
Context is set up in three steps. First create: you make a context object with createContext. Second provide: in a parent component you give the value with Context.Provider. Third consume: in a child component you read the value with useContext.
These three steps are the heart of Context. Every descendant inside the Provider can reach the value; the components in between do not need to pass it as a prop. With this structure any part of the app can reach the central value; when the theme changes, all descendants update automatically.
Practice Create a context
Create a context named ThemeContext. Use createContext; the default value is "light". Then log it with console.log(ThemeContext).
Starter code
// Import createContext
// Create ThemeContext with createContext; default "light"
// Log ThemeContextSample solution
import { createContext } from "react";
const ThemeContext = createContext("light");
console.log(ThemeContext);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What problem does Context solve?
const ThemeContext = createContext("light");- Prop drilling Correct answer
- Style conflicts
- Component naming
- Folder structure
Explanation: Context solves prop drilling.
2 Import Context
import { ____ } from "react";
import { createContext } from "react";
Explanation: createContext is imported from the react package.
3 Match the step to its order
| Term | Meaning |
|---|---|
createContext |
Create |
Provider |
Provide |
useContext |
Consume |
value |
Provided data |