CoastalCommitsPastes/client/lib/hooks/use-theme.ts

28 lines
715 B
TypeScript
Raw Normal View History

import { useCallback, useEffect } from "react"
import useSharedState from "./use-shared-state"
const useTheme = () => {
2022-03-23 18:42:22 -04:00
const isClient = typeof window === "object"
const [themeType, setThemeType] = useSharedState<string>("theme", "light")
2022-03-23 18:42:22 -04:00
useEffect(() => {
if (!isClient) return
const storedTheme = localStorage.getItem("drift-theme")
if (storedTheme) {
setThemeType(storedTheme)
}
}, [isClient, setThemeType])
2022-03-23 18:42:22 -04:00
const changeTheme = useCallback(() => {
setThemeType((last) => {
const newTheme = last === "dark" ? "light" : "dark"
localStorage.setItem("drift-theme", newTheme)
return newTheme
})
}, [setThemeType])
2022-03-23 18:42:22 -04:00
return { theme: themeType, changeTheme }
}
2022-03-23 18:34:23 -04:00
export default useTheme