Last active
May 31, 2021 19:25
-
-
Save YussufElarif/af633536979f15eac8288553c987118e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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