Install

npm
npm i use-any-hook

Description

The useDarkMode hook provides a simple way to toggle between dark and light themes in your application. It manages the theme state and automatically applies the appropriate class to the body element, ensuring that the entire page reflects the selected theme. This is particularly useful for adding dark mode support to your application with minimal setup.

Parameters

This hook does not require any parameters.

Return Values

NameTypeDescription
isDarkModebooleanA boolean indicating whether the dark mode is currently active (true for dark mode, false for light mode).
toggleTheme() => voidA function to toggle between dark and light themes. This also updates the body tag’s class name to reflect the current theme.

Example

useDarkMode.example.tsx
import { useDarkMode } from "use-any-hook";

function MyComponent() {
  const { isDarkMode, toggleTheme } = useDarkMode();

  // toggleTheme() function toggles the global
  // body-tag className automatically.
  // e.g. <body className="dark"></body>

  return (
    <div className={isDarkMode ? "dark-mode" : "light-mode"}>
      <button onClick={toggleTheme}>Toggle Theme</button>
      {isDarkMode ? "Dark Mode" : "Light Mode"}
    </div>
  );
}