I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this:
const TailwindProvider: React.FC = ({ children }) => {
const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme());
console.log("CurrentColorScheme:", currentColorScheme);
const isDarkMode = currentColorScheme == "dark";
const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode))
return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}
as you can see, i use the Appearance.getColorScheme()
method from react-native
to get the current ColorScheme. But both on iOS and Android, i always get light
instead of dark
, in debug as well as in production mode.
How can I fix this?
The problem with useState(Appearance.getColorScheme())
is that it will only be checked once when the app is loaded. You can try the useColorScheme()
hook to keep up to date:
// ...
import { useColorScheme } from 'react-native';
const TailwindProvider: React.FC = ({ children }) => {
const currentColorScheme = useColorScheme();
console.log({ currentColorScheme });
const isDarkMode = currentColorScheme === "dark";
const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode));
return <TailwindContext.Provider value={{ currentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}