Skip to content

Instantly share code, notes, and snippets.

@ChronSyn
Last active February 15, 2021 01:41
Show Gist options
  • Save ChronSyn/c8fd59dcf99c5018e5b4209c00f99985 to your computer and use it in GitHub Desktop.
Save ChronSyn/c8fd59dcf99c5018e5b4209c00f99985 to your computer and use it in GitHub Desktop.
React Native - useTheme hook
import { ITheme } from "@Themes/interfaces";
import { DarkTheme } from "@Themes/theme.dark";
import { LightTheme } from "@Themes/theme.light";
import React from "react";
import { useColorScheme } from "react-native-appearance";
export const useTheme = (): [ITheme] => {
const scheme = useColorScheme();
const [currentTheme, setCurrentTheme] = React.useState<ITheme>(DarkTheme);
React.useEffect(() => {
setCurrentTheme(scheme === "dark" ? DarkTheme : LightTheme);
}, [scheme]);
return [currentTheme];
};
/**
* This version allows you to override the theme by passing a theme as a parameter to the hook
*/
import { ITheme } from "@Themes/interfaces";
import { DarkTheme } from "@Themes/theme.dark";
import { LightTheme } from "@Themes/theme.light";
import React from "react";
import { useColorScheme } from "react-native-appearance";
export const useTheme = (forceTheme?: ITheme): [ITheme] => {
const scheme = useColorScheme();
const [currentTheme, setCurrentTheme] = React.useState<ITheme>(forceTheme ?? DarkTheme);
React.useEffect(() => {
if (forceTheme){
setCurrentTheme(forceTheme);
} else {
setCurrentTheme(scheme === "dark" ? DarkTheme : LightTheme);
}
}, [scheme, forceTheme]);
return [currentTheme];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment