You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中明暗模式切换问题求助:useDarkMode库使用异常

Fixing Dark Mode Toggle with use-dark-mode Library in React

I spot the issue in your code immediately — you're checking the entire darkMode object returned by the hook instead of its actual boolean state value. Let's fix this step by step:

Step 1: Correct the State Check

The useDarkMode hook returns an object with properties like value (the current dark mode state), enable, disable, and toggle. Your current condition {darkMode ? ... : ...} is checking if the object exists (which it always does), so it never switches to the moon button. You need to reference darkMode.value instead.

Fixed Code

import useDarkMode from 'use-dark-mode';

const DarkModeToggle = () => {
  // Initialize with false (light mode as default)
  const darkMode = useDarkMode(false);

  return (
    <>
      {/* Check the actual boolean state with darkMode.value */}
      {darkMode.value ? (
        <button type="button" onClick={darkMode.disable}> ☀ </button>
      ) : (
        <button type="button" onClick={darkMode.enable}> ☾ </button>
      )}
    </>
  );
};

export default DarkModeToggle;

Bonus: Clean Up with the Built-in toggle Method

For simpler code, use the toggle method provided by the hook instead of handling enable/disable separately:

import useDarkMode from 'use-dark-mode';

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

  return (
    <button type="button" onClick={darkMode.toggle}>
      {darkMode.value ? '☀' : '☾'}
    </button>
  );
};

export default DarkModeToggle;

Critical: Set Up Your Theme Styles

Remember that the use-dark-mode library automatically adds a dark class to the <html> element when dark mode is enabled. You need corresponding CSS to actually switch the visual theme, for example:

/* Light mode (default) */
body {
  background-color: #fff;
  color: #111;
  transition: all 0.3s ease;
}

/* Dark mode */
.dark body {
  background-color: #111;
  color: #fff;
}

Why Your Custom Hook Attempt Might Have Failed

If you tried building a custom hook earlier, common missteps include:

  • Not persisting state to localStorage (the use-dark-mode library handles this out of the box)
  • Forgetting to sync the state with the dark class on the <html> element
  • Mishandling the toggle logic between boolean states

内容的提问来源于stack exchange,提问作者helpmepie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:17:33