Open betula opened 3 years ago
import React, { useState, useCallback, useEffect } from "react"; import { useBetween } from "use-between"; const useDarkModeState = () => { const [isDark, setDark] = useState( localStorage.getItem("darkMode") ); useEffect( () => localStorage.setItem("darkMode", isDark ? "true" : ""), [isDark] ); const toggle = useCallback( () => setDark((state) => !state), [setDark] ); return { isDark, toggle }; }; export const useDarkMode = () => useBetween(useDarkModeState);
const Button = () => { const { isDark, toggle } = useDarkMode(); return ( <button style={{ ...styles.button, ...(isDark ? styles.buttonDark : null) }} onClick={toggle} > Switch </button> ); };
const App = () => { const { isDark } = useDarkMode(); return ( <div style={{ ...styles.app, ...(isDark ? styles.appDark : null) }} > {/* ... */} </div> ); };