0

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?

Niklas
  • 1,638
  • 4
  • 19
  • 48

2 Answers2

0

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>;
}
Alex
  • 676
  • 9
  • 20
0

It is stated that 'light' is returned in both debugging AND production code. However, a possible cause for only returning 'light' is if Chrome debugging is used. Per the docs page: [https://reactnative.dev/docs/appearance][1]

"Note: getColorScheme() will always return light when debugging with Chrome."

This could also apply to the useColorScheme() hook if used.

Also, if there is App.json, userInterfaceStyle should be set to automatic for both IOS and Android.