React Native
useContext
Learn to consume context with useContext.
What is useContext?
useContext is the hook that reads a value from a context. When you write const theme = useContext(ThemeContext) you get the value provided by the nearest Provider. If no Provider exists, the context's default value is returned.
A component using useContext re-renders automatically when the context value changes. This removes the need to pass data via props. useContext always reads the value of the nearest Provider; if Providers nest, the innermost one wins. Import the hook from the react package: import { useContext } from "react".
Using useContext
To call useContext you first import the relevant context. Then you write const theme = useContext(ThemeContext). After that the theme variable works like a state; but updates happen not with setState but by changing the Provider's value.
An important point: every time you call useContext, React subscribes that component to context changes. When the Provider's value changes, all subscribed components re-render. So keep context only for truly global data; for frequently changing values that only a few components care about, state may be a better fit.
Exercise Read the theme with useContext
Write a ThemedText component. Read the theme value from ThemeContext with useContext. The component returns <Text>{theme}</Text>. Define ThemeContext outside.
Show example solution
import { createContext, useContext } from "react";
import { Text } from "react-native";
const ThemeContext = createContext("light");
function ThemedText() {
const theme = useContext(ThemeContext);
return <Text>{theme}</Text>;
}
Test yourself
-
What does useContext return?
const theme = useContext(ThemeContext);
- The Provider component
- Always the default value
- Context nesnesini
- The nearest Provider's value
Show answer
The nearest Provider's value — useContext returns the value of the nearest Provider.
-
Call useContext
const theme = ____(ThemeContext);
Show answer
const theme = useContext(ThemeContext);
-
Match the concept to its role
- useContext
- Reads the value
- ThemeContext
- Context object
- Provider
- Provides the value
- theme
- Read value
Next lesson: Context default