Learn how to implement a beautiful dark mode that your users will love, with smooth transitions and proper theming magic.
Dark mode isn't just a trendβit's a necessity for modern apps. Let's implement a beautiful dark mode that your users will absolutely love!
First, let's create a theme context:
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
};
export const ThemeProvider = ({ children }) => {
const [isDark, setIsDark] = useState(false);
const theme = {
isDark,
colors: isDark ? darkColors : lightColors,
toggleTheme: () => setIsDark(!isDark),
};
return (
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
);
};
Define your color palettes:
const lightColors = {
background: '#FFFFFF',
surface: '#F5F5F5',
primary: '#6366F1',
text: '#1F2937',
textSecondary: '#6B7280',
border: '#E5E7EB',
};
const darkColors = {
background: '#111827',
surface: '#1F2937',
primary: '#818CF8',
text: '#F9FAFB',
textSecondary: '#D1D5DB',
border: '#374151',
};
Add smooth transitions:
import { Animated } from 'react-native';
const AnimatedThemeContainer = ({ children }) => {
const { isDark } = useTheme();
const animatedValue = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(animatedValue, {
toValue: isDark ? 1 : 0,
duration: 300,
useNativeDriver: false,
}).start();
}, [isDark]);
const backgroundColor = animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [lightColors.background, darkColors.background],
});
return (
<Animated.View style={[styles.container, { backgroundColor }]}>
{children}
</Animated.View>
);
};
Respect user's system preferences:
import { useColorScheme } from 'react-native';
export const ThemeProvider = ({ children }) => {
const systemColorScheme = useColorScheme();
const [themeMode, setThemeMode] = useState('system'); // 'light', 'dark', 'system'
const isDark = useMemo(() => {
if (themeMode === 'system') {
return systemColorScheme === 'dark';
}
return themeMode === 'dark';
}, [themeMode, systemColorScheme]);
// Rest of the implementation...
};
Sweet dreams with dark mode! π
Help us improve our documentation