Theme context
- React Native course
- Intermediate
- Lesson 83/116
- 5 min
Learn theme management with Context.
Theme context
The theme is shared data reached by every component. So it is kept in a Context. createContext() creates a context; Provider spreads the theme value.
The Provider gives the current theme object as its value. Components reach the theme with useContext; they read colors without prop drilling. The theme is managed from a single point.
ThemeProvider
ThemeProvider is the component that holds and spreads the theme. It keeps the theme state and gives it to children with <ThemeContext.Provider value={theme}>. It wraps the outside of the app. This way the theme is managed from a single source.
So every child component reaches the theme with useContext(ThemeContext). When the theme changes, the Provider spreads the new value; all components update.
Practice Add ThemeContext and ThemeProvider
Add a ThemeContext and a ThemeProvider. Inside the Provider use const [theme, setTheme] = useState(light) and <ThemeContext.Provider value={theme}>. light is defined.
Starter code
import React, { createContext, useState } from 'react';
import { View } from 'react-native';
const light = { background: '#fff', text: '#000' };
// Add ThemeContext and ThemeProvider
export default function App() {
return <View />;
}Sample solution
import React, { createContext, useState } from 'react';
import { View } from 'react-native';
const light = { background: '#fff', text: '#000' };
const ThemeContext = createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = useState(light);
return (
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
);
}
export default function App() {
return (
<ThemeProvider>
<View />
</ThemeProvider>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 createContext call
const ThemeContext = ____();
const ThemeContext = createContext();
Explanation: createContext creates a context.
2 What does ThemeProvider do?
- Generates colors
- Draws a list
- Spreads the theme to children Correct answer
- Sets up navigation
Explanation: ThemeProvider spreads the theme to children via the Provider.
3 Match the theme context concepts
| Term | Meaning |
|---|---|
createContext |
Creates context |
ThemeProvider |
Spreads theme |
useContext |
Reaches theme |
Provider |
Gives value |