In this lesson, you will learn how to make your app automatically switch between light and dark modes by detecting the user's system preferences.
Why Context-Aware Themes Matter
Most modern mobile devices have a "System Theme" setting that users toggle based on the time of day or personal preference. Instead of forcing a single look, a context-aware app observes this setting and adjusts its colors dynamically. This creates a professional, polished experience that feels like a natural extension of the user's operating system.
Detecting System Appearance
React Native provides a built-in module called useColorScheme. This hook returns a string—either 'light', 'dark', or null—that represents the user's current device preference. Because it is a React hook, your component will automatically re-render whenever the user flips their system setting, ensuring your UI stays perfectly synced.
Implementing the Dynamic Theme
You can use the value from useColorScheme to pick colors from a style object. Here is a simple implementation:
import React from 'react';
import { View, Text, useColorScheme, StyleSheet } from 'react-native';
const ThemeAwareScreen = () => {
const theme = useColorScheme();
// Define colors based on the current theme
const backgroundColor = theme === 'dark' ? '#121212' : '#FFFFFF';
const textColor = theme === 'dark' ? '#FFFFFF' : '#000000';
return (
<View style={[styles.container, { backgroundColor }]}>
<Text style={{ color: textColor }}>
Current theme: {theme}
</Text>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' }
});
In this example, we aren't just setting a static style. We are calculating backgroundColor and textColor on the fly. If the user changes their phone settings from Light to Dark while your app is open, the theme variable updates instantly, the component re-renders, and the UI shifts to the new color palette without any extra work from you.
Key Takeaway: Use the useColorScheme hook to reactively track system appearance and update your component styles in real-time, ensuring your app always matches the user's environment.