Course contentsShow
← React Native
Lesson 285 of 1,5554. Flexbox and Native StylingFree lesson

System-Native Dark Mode Integration

Synchronize component colors with user system-level theme preferences.

In this lesson, you will learn how to detect the user's system-wide theme preference and synchronize your application’s colors to respect those settings automatically.

Understanding System Themes

When users switch their phone from Light Mode to Dark Mode, they expect your app to follow suit. Instead of forcing a single color palette, we treat the system theme as a dynamic variable. By tapping into the device’s appearance settings, we can ensure our application feels like a native extension of the operating system.

Detecting the Theme

React Native provides a built-in module called useColorScheme. This hook returns a string—either 'light', 'dark', or null—based on the user's current device preference. Because this is a hook, your component will automatically re-render whenever the user toggles their system setting, allowing for a seamless transition.

Implementing Dynamic Colors

To keep your code clean, avoid hardcoding colors directly in your JSX. Instead, use the hook to select a theme object, then apply those colors to your styles.

import { useColorScheme, View, Text, StyleSheet } from 'react-native';

const ThemeApp = () => {
  const deviceTheme = useColorScheme();
  
  // Define colors based on the current theme
  const isDarkMode = deviceTheme === 'dark';
  const themeStyles = {
    backgroundColor: isDarkMode ? '#121212' : '#FFFFFF',
    textColor: isDarkMode ? '#FFFFFF' : '#000000',
  };

  return (
    <View style={[styles.container, { backgroundColor: themeStyles.backgroundColor }]}>
      <Text style={{ color: themeStyles.textColor }}>
        Hello! You are currently using {deviceTheme} mode.
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' }
});

By placing the theme-specific colors inside your style array, you ensure that the UI updates immediately when the user changes their system preferences. This approach avoids the need for a custom app-wide state manager for basic appearance, keeping your component logic lightweight and performant.

Key Takeaway: Use the useColorScheme hook to bridge your application styling with the user’s device settings, ensuring your UI remains consistent with the system-wide appearance.