useColorScheme
- React Native course
- Intermediate
- Lesson 85/116
- 5 min
Learn the system theme with useColorScheme.
useColorScheme
useColorScheme is a built-in hook that reads the operating system's light/dark preference. It returns 'light', 'dark' or null. When the user changes the setting, the value updates at once.
Example: const scheme = useColorScheme(). With scheme === 'dark' you can pick the dark theme. This suits starting from the user's system preference.
Practice Pick a theme with useColorScheme
Read the system preference with useColorScheme: const scheme = useColorScheme(). Then pick the theme with const theme = scheme === 'dark' ? dark : light. light and dark are defined.
Starter code
import React from 'react';
import { Text, View } from 'react-native';
const light = { background: '#fff', text: '#000' };
const dark = { background: '#000', text: '#fff' };
export default function App() {
// Read the system preference with useColorScheme
const theme = light;
return (
<View style={{ backgroundColor: theme.background }}>
<Text style={{ color: theme.text }}>Theme</Text>
</View>
);
}Sample solution
import React from 'react';
import { Text, View, useColorScheme } from 'react-native';
const light = { background: '#fff', text: '#000' };
const dark = { background: '#000', text: '#fff' };
export default function App() {
const scheme = useColorScheme();
const theme = scheme === 'dark' ? dark : light;
return (
<View style={{ backgroundColor: theme.background }}>
<Text style={{ color: theme.text }}>Theme</Text>
</View>
);
}System preference
useColorScheme respects the user's operating system setting. If the phone is in dark mode it returns 'dark'; in light mode 'light'. When the user changes the setting, the hook updates at once.
Using the system preference at launch is a good starting point. The user can later change it with a toggle. This way the app matches the look the user is already used to.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useColorScheme return?
- The system's light/dark preference Correct answer
- A component
- A color
- A list
Explanation: useColorScheme returns the system's light/dark preference.
2 useColorScheme call
const scheme = ____();
const scheme = useColorScheme();
Explanation: useColorScheme() gives the system preference.
3 Match the useColorScheme concepts
| Term | Meaning |
|---|---|
useColorScheme |
System preference |
light |
Light mode |
dark |
Dark mode |
scheme |
Preference value |