Skip to main content

useDarkMode

dark mode with auto data persistence.

Usage

Live Editor

function Demo() {
  const [theme, toggleDark] = useDarkMode({
    classNameDark: "dark",
    classNameLight: "light",
    defaultValue: false,
  });

  return (
    <div>
      <div>theme: {theme ? "dark" : "light"}</div>
      <br />
      <div>
        <button onClick={toggleDark}>toggleDark</button>
      </div>
    </div>
  );
};

Result
Loading...

API

UseDarkOptions

PropertyDescriptionTypeDefaultValue
selectorCSS Selector for the target element applying tostring'html'
attributeHTML attribute applying the target elementstring'class'
defaultValuedefault valuebooleanfalse
storageKeyKey to persist the data into localStorage/sessionStorage.string'reactuses-color-scheme'
storageStorage object, can be localStorage or sessionStorage() => StoragelocalStorage
classNameDarkname dark apply to elementstring (Required)-
classNameLightname light apply to elementstring (Required)-

useDarkMode

Returns

readonly [boolean | null, () => void, React.Dispatch<React.SetStateAction<boolean | null>>]: A tuple with the following elements:

  • The current value of the dark state.
  • A function to toggle the dark state.
  • A function to update the dark state.

Arguments

ArgumentDescriptionTypeDefaultValue
options-UseDarkOptions (Required)-