Skip to content

Instantly share code, notes, and snippets.

@YussufElarif
Last active May 31, 2021 19:25
Show Gist options
  • Save YussufElarif/af633536979f15eac8288553c987118e to your computer and use it in GitHub Desktop.
Save YussufElarif/af633536979f15eac8288553c987118e to your computer and use it in GitHub Desktop.
import React, { createContext, useCallback, useContext, useMemo, useState } from "react";
import { useColorScheme } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage"
import { dark, light } from "../../utls/layout";
const ThemeContext = createContext(undefined);
export default function ThemeContextProvider({ children }) {
const systemColorScheme = useColorScheme();
const getTheme = useCallback((colorScheme) => {
return colorScheme === "dark" ? dark : light;
}, [])
const colorScheme = useMemo(() => {
return AsyncStorage.getItem("colorScheme") ?? systemColorScheme;
}, [systemColorScheme])
const setColorScheme = useCallback((colorScheme) => {
AsyncStorage.setItem("colorScheme", colorScheme)
setTheme(getTheme(colorScheme))
}, [getTheme])
const [theme, setTheme] = useState(getTheme(colorScheme));
return (
<ThemeContext.Provider value={[theme, setColorScheme]}>
{children}
</ThemeContext.Provider>
)
}
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme can only be used within ThemeContextProvider")
}
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment