React Native
Context default
Learn context default values and fallback.
What is the default value?
The default value of a context is the value that useContext returns when a component is not inside any Provider. When you write createContext("light"), this default becomes "light".
The default value is used for two purposes. First to give a real starting value: even with no Provider at the root, components keep working. Second to catch mistakes: if you do createContext(null) and a child gets null, you forgot the Provider; this is easy to spot. Which path you choose depends on whether you prefer catching mistakes or flexible running.
Catch mistakes with a null default
Some teams prefer to write createContext(null). With this approach, if a component is used outside a Provider, useContext returns null; the developer notices the mistake at once.
Forgetting a Provider is easy in large apps. When null is returned and a child calls theme.toUpperCase(), it throws; this gives an early warning instead of a silently broken screen. So many teams set the default to null to catch mistakes early. As long as you make sure a Provider exists at the root, this approach works well.
Exercise Use the default value
Create a context named LangContext. Use createContext(null). Then write a Picker component; read lang with useContext(LangContext) and log it with console.log(lang).
Show example solution
import { createContext, useContext } from "react";
const LangContext = createContext(null);
function Picker() {
const lang = useContext(LangContext);
console.log(lang);
return null;
}
Test yourself
-
Give a default value
const ThemeContext = createContext(____);
Show answer
const ThemeContext = createContext("light");
-
Match the scenario to the outcome
- Provider exists
- Provider value returns
- No Provider, default null
- null returns
- No Provider, default "light"
- light returns
- useContext call
- Reads the value
-
When is createContext(null) useful?
const ThemeContext = createContext(null);
- AsyncStorage yerine
- To warn early when the Provider is missing
- For every component's default theme
- To share styles
Show answer
To warn early when the Provider is missing — A null default warns early when a Provider is forgotten.
Next lesson: Summary - Context