DEV Community

Cover image for React Custom Hook: useDarkSwitch
Olaniyi Olabode
Olaniyi Olabode

Posted on

React Custom Hook: useDarkSwitch

In a world where users increasingly demand personalized experiences, enabling a smooth and effortless dark mode toggle for your application is no longer just an optional enhancement it's a necessity. Enter useDarkSwitch, the custom React hook that does all the heavy lifting for you. Seamlessly toggle between light and dark themes, sync with system preferences, and enhance your app’s user experience with a robust and intuitive API.

Whether you're building a sleek portfolio website, a productivity app, or a complex dashboard, useDarkSwitch is the perfect utility to elevate your project. Let’s dive into why this hook is a game changer for developers.

Why You Need useDarkSwitch

Dark mode isn’t just a trend it’s a user expectation. Beyond aesthetics, it reduces eye strain, conserves battery life on OLED screens, and adapts to the user’s environment. Implementing a reliable dark mode solution, however, can be surprisingly tricky. That’s where useDarkSwitch comes in.

Here’s why you’ll love it:

  1. Developer Friendly: Intuitive API with sensible defaults, so you can integrate it in minutes.
  2. Customizable: Tailor it to your application’s needs with options for storage providers, class names, and transition durations.
  3. Sync with System Preferences: Automatically adapt to the user’s system theme settings.
  4. Persist User Preferences: Save and retrieve the theme mode with localStorage or a custom storage provider.
  5. Responsive and Accessible: Ensure your app stays relevant to a diverse audience.

Features of useDarkSwitch

1. Effortless Integration

Setting up useDarkSwitch is straightforward. With minimal configuration, you can have a fully functional theme toggle up and running:

import { useDarkSwitch } from 'use-dark-switch';

function App() {
  const { isDark, toggle } = useDarkSwitch();

  return (
    <div>
      <button onClick={toggle}>
        Switch to {isDark ? 'Light' : 'Dark'} Mode
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This simplicity empowers you to focus on your app’s core functionality while delivering an elevated user experience.

2. Full Customizability

Customize every aspect of the hook to suit your app’s requirements:

const { isDark, enable, disable } = useDarkSwitch({
  defaultMode: false,
  storageKey: 'my-theme',
  classNameDark: 'my-dark-mode',
  classNameLight: 'my-light-mode',
  transitionDuration: 500,
});
Enter fullscreen mode Exit fullscreen mode
  • Default Mode: Set the initial theme.
  • Storage Key: Define a custom key for saving user preferences.
  • Class Names: Apply custom styles for your themes.
  • Transition Duration: Smoothly animate theme changes.

3. Sync with System Theme

Modern users expect apps to reflect their system preferences. With useDarkSwitch, you can achieve this effortlessly:

const { systemTheme } = useDarkSwitch({ syncWithSystem: true });
Enter fullscreen mode Exit fullscreen mode

The hook listens to system theme changes in real-time, ensuring your app remains in sync without additional overhead.

4. Custom Storage Providers

Need to store preferences in a unique way, such as a server-side session or an IndexedDB instance? useDarkSwitch supports custom storage providers:

const customStorage = {
  getItem: (key) => sessionStorage.getItem(key),
  setItem: (key, value) => sessionStorage.setItem(key, value),
  removeItem: (key) => sessionStorage.removeItem(key),
};

const { isDark } = useDarkSwitch({ storageProvider: customStorage });
Enter fullscreen mode Exit fullscreen mode

5. Callback Support

Leverage the onChange callback to execute additional logic whenever the theme changes:

const { toggle } = useDarkSwitch({
  onChange: (isDark) => {
    console.log(`Theme changed to: ${isDark ? 'Dark' : 'Light'}`);
  },
});
Enter fullscreen mode Exit fullscreen mode

This makes it easier to integrate analytics, logging, or other side effects.

6. Smooth Transitions

Enhance user experience by adding transitions to theme changes. Define a duration, and useDarkSwitch handles the rest:

const { toggle, isTransitioning } = useDarkSwitch({ transitionDuration: 300 });

return (
  <button onClick={toggle} disabled={isTransitioning}>
    Toggle Theme
  </button>
);
Enter fullscreen mode Exit fullscreen mode

SEO Benefits of Adding Dark Mode

Implementing dark mode using useDarkSwitch can indirectly improve your app’s search engine rankings. How? By boosting user experience and engagement metrics. When users spend more time on your site and interact with its features, search engines take note. A happy user often equals better SEO performance.

The Future of Theming in React

useDarkSwitch embodies the future of React development—modular, customizable, and user-focused. As the ecosystem evolves, such utilities will become indispensable for creating modern, responsive, and accessible applications.

Get Started Today

Ready to level up your React app? Install useDarkSwitch and start building:

npm install use-dark-switch
Enter fullscreen mode Exit fullscreen mode

Join the growing community of developers who trust useDarkSwitch to deliver seamless dark mode functionality. For detailed documentation, visit the GitHub repository.


With useDarkSwitch, theming has never been this elegant. Embrace the power of dark mode and watch your app shine or, in this case, darken! Start building smarter, more intuitive experiences today.

Top comments (0)