betula / use-between

Sharing state between React components
MIT License
285 stars 11 forks source link

How to make dark mode switcher #12

Open betula opened 3 years ago

betula commented 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);

Try dark mode with useBetween

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>
  );
};