1.0.1 • Published 2 years ago

@utilityjs/use-dark-mode v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

A React hook that enables a SSR-friendly multi-tab persistent dark mode behaviour.\

license npm latest package npm downloads types

npm i @utilityjs/use-dark-mode | yarn add @utilityjs/use-dark-mode

Usage

const App: React.FC = () => {
  const { isDarkMode, toggle } = useDarkMode();

  return (
    <div className="app">
      <button onClick={() => void toggle()}>Toggle</button>
      <div>{isDarkMode}</div>
    </div>
  );
};

API

useDarkMode(options?)

interface Options {
  /**
   * The initial state of the dark mode.\
   * If left unset, it will be set based on `(prefers-color-scheme: dark)` query.
   */
  initialState?: boolean;
  /**
   * The key is used to persist the state.
   *
   * @default "utilityjs-dark-mode"
   */
  storageKey?: string;
  /**
   * The class to toggle when state changes.\
   * The specified class will be applied on dark mode.
   *
   * @default "dark-mode"
   */
  toggleClassName?: string;
  /**
   * A function returning a storage.\
   * The storage must fit `window.localStorage`'s api.
   *
   * @default () => localStorage
   */
  getStorage?: () => Storage | null;
}

declare const useDarkMode: (options?: Options | undefined) => {
  isDarkMode: boolean;
  enable: () => void;
  disable: () => void;
  toggle: () => void;
};

options

The options to adjust the hook.

options.storageKey - (default: "utilityjs-dark-mode")

The key is used to persist the state.

options.initialState

The initial state of the dark mode.\ If left unset, it will be set based on (prefers-color-scheme: dark) query.

options.getStorage - (default: () => localStorage)

A function returning a storage.\ The storage must fit window.localStorage's api.

options.toggleClassName - (default: "dark-mode")

The class to toggle when state changes.\ The specified class will be applied on dark mode.