@fisch0920/use-dark-mode

中文文档
2.4.0发布于 2022/03/31MITTypeScriptESM + CJS近 30 天下载 4088

A custom React Hook to help you implement a "dark mode" component.

原始使用文档
文档目录12 节
  1. New in Version 2.x
  2. Requirement
  3. Installation
  4. Usage
  5. Parameters
  6. Return object
  7. Example
  8. That flash!
  9. Gatsby
  10. Next.js
  11. License
  12. Contributors

@fisch0920/use-dark-mode

NOTE: this is a fork of use-dark-mode by donovan which adds some much needed maintenance support for React 17 and 18.

A custom React Hook to help you implement a "dark mode" component for your application. The user setting persists to localStorage.

❤️ it? ⭐️ it on GitHub

npm version All Contributors

usedarkmode-small

useDarkMode works in one of two ways:

  1. By toggling a CSS class on whatever element you specify (defaults to document.body). You then setup your CSS to display different views based on the presence of the selector. For example, the following CSS is used in the demo app to ease the background color in/out of dark mode.

    body.light-mode {
      background-color: #fff;
      color: #333;
      transition: background-color 0.3s ease;
    }
    body.dark-mode {
      background-color: #1a1919;
      color: #999;
    }
    
  2. If you don't use global classes, you can specify an onChange handler and take care of the implementation of switching to dark mode yourself.

New in Version 2.x

  • useDarkMode now persists between sessions. It stores the user setting in localStorage.

  • It shares dark mode state with all other useDarkMode components on the page.

  • It shares dark mode state with all other tabs/browser windows.

  • The initial dark mode is queried from the system. Note: this requires a browser that supports the prefers-color-scheme: dark media query (currently Chrome, Firefox, Safari and Edge) and a system that supports dark mode, such as macOS Mojave.

  • Changing the system dark mode state will also change the state of useDarkMode (i.e, change to light mode in the system will change to light mode in your app).

  • Support for Server Side Rendering (SSR) in version 2.2 and above.

Requirement

To use @fisch0920/use-dark-mode, you must use [email protected] or greater which includes Hooks.

Installation

$ npm i @fisch0920/use-dark-mode

Usage

const darkMode = useDarkMode(initialState, darkModeConfig);

Parameters

You pass useDarkMode an initialState (a boolean specifying whether it should be in dark mode by default) and an optional darkModeConfig object. The configuration object may contain the following keys.

KeyDescription
classNameDarkThe class to apply. Default = dark-mode.
classNameLightThe class to apply. Default = light-mode.
elementThe element to apply the class name. Default = document.body.
onChangeA function that will be called when the dark mode value changes and it is safe to access the DOM (i.e. it is called from within a useEffect). If you specify onChange then classNameDark, classNameLight, and element are ignored (i.e. no classes are automatically placed on the DOM). You have full control!
storageKeyA string that will be used by the storageProvider to persist the dark mode value. If you specify a value of null, nothing will be persisted. Default = darkMode.
storageProviderA storage provider. Default = localStorage. You will generally never need to change this value.

Return object

A darkMode object is returned with the following properties.

KeyDescription
valueA boolean containing the current state of dark mode.
enable()A function that allows you to set dark mode to true.
disable()A function that allows you to set dark mode to false.
toggle()A function that allows you to toggle dark mode.

Note that because the methods don't require any parameters, you can call them direcly from an onClick handler from a button, for example (i.e., no lambda function is required).

Example

Here is a simple component that uses useDarkMode to provide a dark mode toggle control. If dark mode is selected, the CSS class dark-mode is applied to document.body and is removed when de-selected.

import React from 'react';
import useDarkMode from '@fisch0920/use-dark-mode';

import Toggle from './Toggle';

const DarkModeToggle = () => {
  const darkMode = useDarkMode(false);

  return (
    <div>
      <button type="button" onClick={darkMode.disable}>
        ☀
      </button>
      <Toggle checked={darkMode.value} onChange={darkMode.toggle} />
      <button type="button" onClick={darkMode.enable}>
        ☾
      </button>
    </div>
  );
};

export default DarkModeToggle;

That flash!

If your CSS is setup to default to light mode, but the user selects dark mode, the next time they visit your app, they will be in dark mode. However, the user will see a flash of light mode before the app is spun up and useDarkMode is called.

To prevent this, I've included some vanilla JavaScript that you can insert in your index.html just after the <body> tag. It is in a file named noflash.js.txt. You can either insert the contents of this file in a <script> tag or automate the step in your build process.

Note that if you change any of the default—such as storageKey or classNameDark for example—the noflash.js file will need to be modified with the same values.

Gatsby

Gatsby users may leverage gatsby-plugin-use-dark-mode to inject noflash.js for you.

Next.js

For next.js uses copy the noflash.js.txt to your public folder (public/noflash.js) and then create a _document.js and include the script before <Main />.

import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head />
        <body>
          <script src="noflash.js" />
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

License

MIT Licensed

Contributors

Thanks goes to these wonderful people (emoji key):


Donavon West

🚇 ⚠️ 💡 🤔 🚧 👀 🔧 💻

Revel Carlberg West

🤔

Mateusz Burzyński

💻

Justin Hall

💻

Jeremy

📓 🐛

Janosh Riebesell

📖

Andrew Lisowski

📖

Jorge Gonzalez

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

版本与发布记录

@fisch0920/use-dark-mode 共发布 2 个版本,首次发布于 2022/03/31;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.4.0latest2022/03/314 年前
2.3.22022/03/314 年前

关于 @fisch0920/use-dark-mode 的常见问题

@fisch0920/use-dark-mode 是什么?

A custom React Hook to help you implement a "dark mode" component.

如何安装 @fisch0920/use-dark-mode?

在项目目录运行 npm install @fisch0920/use-dark-mode,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=16.8)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fisch0920/use-dark-mode 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fisch0920/use-dark-mode 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@fisch0920/use-dark-mode 可以商用吗?

@fisch0920/use-dark-mode 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fisch0920/use-dark-mode 的下载量有多少?

根据 npm 官方下载统计,@fisch0920/use-dark-mode 在 2026/10/15 – 2026/11/13 这 30 天内被下载 4,088 次,日均约 136 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fisch0920/use-dark-mode 还在维护吗?

最新版本 2.4.0 发布于 2022/03/31(4 年前);至今共发布 2 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/03/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。