Skip to content

Instantly share code, notes, and snippets.

@AhmetEnesKCC
Created March 19, 2022 13:42
Show Gist options
  • Save AhmetEnesKCC/63d02d9c0bb6774f978526d2c0e82ba8 to your computer and use it in GitHub Desktop.
Save AhmetEnesKCC/63d02d9c0bb6774f978526d2c0e82ba8 to your computer and use it in GitHub Desktop.
set sytem theme related to system custom-hook
import {useState, useEffect} from "react";
import {getSystemTheme, watchSytemTheme, setTheme as setWebsiteTheme } from "functions-path" // you need export them separately. I changed name for prevent name collision with local state below.
// Creating custom hook - must be 'use' at the starting of function name
const useSetThemeRelatedToSystem = () => {
// create theme state
const [theme,setTheme] = useState("dark") // I prefer dark mode to inital state;
// For first time;
useEffect() {
const currentSystemTheme = getSystemTheme();
// This will only set local state above
setTheme(currentSystemTheme);
// This will set the root element's query
setWebsiteTheme(currentSystemTheme)
// Watch for system theme changes
watchSystemTheme();
, []} // empty array to run only on mounting
return {theme} // If you want use theme other stuffs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment