Top Related Projects
Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
A utility-first CSS framework for rapid UI development.
⚡️ Simple, Modular & Accessible UI Components for your React Applications
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
👩🎤 CSS-in-JS library designed for high performance style composition
Build forms in React, without the tears 😭
Quick Overview
use-dark-mode
is a custom React Hook that simplifies the implementation of dark mode in React applications. It provides an easy way to toggle between light and dark themes, persists the user's preference, and offers a clean API for managing dark mode state.
Pros
- Easy to integrate into existing React projects
- Automatically persists user preference using localStorage
- Provides a simple API for toggling and checking dark mode status
- Supports SSR (Server-Side Rendering)
Cons
- Limited to React applications only
- Requires additional setup for global styling changes
- May not be suitable for complex theming requirements
- Depends on the
use-persisted-state
library
Code Examples
- Basic usage of the
useDarkMode
hook:
import useDarkMode from 'use-dark-mode';
function App() {
const darkMode = useDarkMode(false);
return (
<div>
<button onClick={darkMode.toggle}>
Toggle Dark Mode
</button>
<div>Dark mode is {darkMode.value ? 'on' : 'off'}</div>
</div>
);
}
- Using
useDarkMode
with custom initial state and storage key:
const darkMode = useDarkMode(true, {
classNameDark: 'my-dark-mode',
classNameLight: 'my-light-mode',
storageKey: 'myAppDarkMode',
});
- Integrating with CSS-in-JS libraries (e.g., styled-components):
import styled from 'styled-components';
import useDarkMode from 'use-dark-mode';
const StyledComponent = styled.div`
background-color: ${props => props.darkMode ? '#333' : '#fff'};
color: ${props => props.darkMode ? '#fff' : '#333'};
`;
function MyComponent() {
const darkMode = useDarkMode(false);
return (
<StyledComponent darkMode={darkMode.value}>
Content goes here
</StyledComponent>
);
}
Getting Started
-
Install the package:
npm install use-dark-mode
-
Import and use the hook in your React component:
import useDarkMode from 'use-dark-mode'; function MyComponent() { const darkMode = useDarkMode(false); return ( <div> <button onClick={darkMode.toggle}> Switch to {darkMode.value ? 'Light' : 'Dark'} Mode </button> </div> ); }
-
Add CSS classes for light and dark modes in your global styles:
.light-mode { background-color: #fff; color: #333; } .dark-mode { background-color: #333; color: #fff; }
Competitor Comparisons
Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
Pros of Material-UI
- Comprehensive UI component library with a wide range of pre-built components
- Implements Google's Material Design principles for consistent and modern UI
- Active development and large community support
Cons of Material-UI
- Larger bundle size due to its extensive component library
- Steeper learning curve for customization and theming
- May require more setup and configuration for specific use cases
Code Comparison
use-dark-mode:
import useDarkMode from 'use-dark-mode';
const DarkModeToggle = () => {
const darkMode = useDarkMode(false);
return <button onClick={darkMode.toggle}>Toggle dark mode</button>;
};
Material-UI:
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
const darkTheme = createTheme({ palette: { mode: 'dark' } });
const App = () => (
<ThemeProvider theme={darkTheme}>
<CssBaseline />
{/* Your app content */}
</ThemeProvider>
);
Summary
use-dark-mode is a lightweight, focused solution for implementing dark mode in React applications. It provides a simple hook for managing dark mode state and toggling between light and dark themes.
Material-UI, on the other hand, is a full-fledged UI component library that includes theming capabilities, including dark mode support. It offers a more comprehensive solution for building entire user interfaces but comes with additional complexity and a larger footprint.
Choose use-dark-mode for a minimal, easy-to-implement dark mode solution, or Material-UI for a complete UI framework with built-in theming support.
A utility-first CSS framework for rapid UI development.
Pros of Tailwind CSS
- Comprehensive utility-first CSS framework with a vast set of pre-built classes
- Highly customizable and extensible through configuration
- Excellent documentation and community support
Cons of Tailwind CSS
- Steeper learning curve due to its extensive class-based approach
- Potentially larger initial CSS file size before optimization
Code Comparison
use-dark-mode:
import useDarkMode from 'use-dark-mode';
const DarkModeToggle = () => {
const darkMode = useDarkMode(false);
return <button onClick={darkMode.toggle}>Toggle dark mode</button>;
};
Tailwind CSS:
<button class="bg-white dark:bg-gray-800 text-black dark:text-white">
Toggle dark mode
</button>
Summary
Tailwind CSS is a comprehensive utility-first CSS framework, while use-dark-mode is a focused React hook for implementing dark mode. Tailwind CSS offers a wide range of pre-built classes and customization options but may have a steeper learning curve. use-dark-mode provides a simpler, more specific solution for dark mode functionality in React applications. The choice between the two depends on the project's scope and requirements.
⚡️ Simple, Modular & Accessible UI Components for your React Applications
Pros of Chakra UI
- Comprehensive UI component library with a wide range of pre-built components
- Built-in theming system with support for light and dark modes
- Accessibility-focused design with ARIA-compliant components
Cons of Chakra UI
- Larger bundle size due to the extensive component library
- Steeper learning curve for developers new to the ecosystem
- May require more setup and configuration for simple projects
Code Comparison
use-dark-mode:
import useDarkMode from 'use-dark-mode';
const DarkModeToggle = () => {
const darkMode = useDarkMode(false);
return <button onClick={darkMode.toggle}>Toggle dark mode</button>;
};
Chakra UI:
import { useColorMode, Button } from '@chakra-ui/react';
const DarkModeToggle = () => {
const { colorMode, toggleColorMode } = useColorMode();
return <Button onClick={toggleColorMode}>Toggle {colorMode} mode</Button>;
};
Summary
Chakra UI offers a more comprehensive solution for building user interfaces, including a dark mode feature, while use-dark-mode focuses specifically on implementing dark mode functionality. Chakra UI provides a rich set of components and theming options but comes with a larger footprint and complexity. use-dark-mode is simpler and more lightweight, making it suitable for projects that only need dark mode functionality without additional UI components.
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
Pros of styled-components
- More comprehensive CSS-in-JS solution for styling React components
- Supports dynamic styling based on props and themes
- Offers a larger ecosystem with plugins and integrations
Cons of styled-components
- Steeper learning curve due to its more extensive feature set
- Larger bundle size compared to use-dark-mode
- May introduce performance overhead for complex applications
Code Comparison
use-dark-mode:
import useDarkMode from 'use-dark-mode';
const DarkModeToggle = () => {
const darkMode = useDarkMode(false);
return <button onClick={darkMode.toggle}>Toggle dark mode</button>;
};
styled-components:
import styled from 'styled-components';
const Button = styled.button`
background-color: ${props => props.theme.backgroundColor};
color: ${props => props.theme.textColor};
`;
Summary
use-dark-mode is a lightweight hook for implementing dark mode in React applications, while styled-components is a full-featured CSS-in-JS library. use-dark-mode is simpler to use and has a smaller footprint, making it ideal for projects primarily focused on dark mode functionality. styled-components offers more flexibility and power for styling entire applications but comes with increased complexity and bundle size.
👩🎤 CSS-in-JS library designed for high performance style composition
Pros of emotion
- More comprehensive styling solution with broader feature set
- Supports server-side rendering and critical CSS extraction
- Offers a powerful theming system for consistent styling across components
Cons of emotion
- Steeper learning curve due to more complex API
- Larger bundle size compared to use-dark-mode
- May be overkill for simple styling needs or projects focused solely on dark mode
Code Comparison
use-dark-mode:
import useDarkMode from 'use-dark-mode';
const DarkModeToggle = () => {
const darkMode = useDarkMode(false);
return <button onClick={darkMode.toggle}>Toggle Dark Mode</button>;
};
emotion:
import { css } from '@emotion/react';
const button = css`
background-color: ${props => props.theme.colors.primary};
color: white;
padding: 10px 20px;
`;
const DarkModeToggle = () => (
<button css={button} onClick={toggleDarkMode}>Toggle Dark Mode</button>
);
Summary
emotion is a full-featured CSS-in-JS library that provides a comprehensive styling solution, while use-dark-mode is a focused hook for implementing dark mode functionality. emotion offers more flexibility and power for styling entire applications, but may be excessive for projects only needing dark mode support. use-dark-mode is simpler to implement and has a smaller footprint, making it ideal for projects specifically focused on dark mode toggling.
Build forms in React, without the tears 😭
Pros of Formik
- More comprehensive form management solution, handling state, validation, and submission
- Larger community and ecosystem, with extensive documentation and third-party integrations
- Reduces boilerplate code for complex form scenarios
Cons of Formik
- Steeper learning curve due to its more extensive API and features
- Potentially overkill for simple form implementations
- Larger bundle size compared to use-dark-mode
Code Comparison
use-dark-mode:
import useDarkMode from 'use-dark-mode';
const DarkModeToggle = () => {
const darkMode = useDarkMode(false);
return <button onClick={darkMode.toggle}>Toggle dark mode</button>;
};
Formik:
import { Formik, Form, Field } from 'formik';
const MyForm = () => (
<Formik initialValues={{ email: '' }} onSubmit={handleSubmit}>
<Form>
<Field name="email" type="email" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
While use-dark-mode focuses on a specific functionality (dark mode toggling), Formik provides a comprehensive solution for form management. use-dark-mode is simpler to implement for its specific use case, while Formik offers more power and flexibility for complex form scenarios at the cost of increased complexity.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
use-dark-mode
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 or Tweet about it.
useDarkMode
works in one of two ways:
-
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; }
-
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 inlocalStorage
. -
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 use-dark-mode
, you must use react@16.8.0
or greater which includes Hooks.
Installation
$ npm i 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.
Key | Description |
---|---|
classNameDark | The class to apply. Default = dark-mode . |
classNameLight | The class to apply. Default = light-mode . |
element | The element to apply the class name. Default = document.body . |
onChange | A 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! |
storageKey | A 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 . |
storageProvider | A storage provider. Default = localStorage . You will generally never need to change this value. |
Return object
A darkMode
object is returned with the following properties.
Key | Description |
---|---|
value | A 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 '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;
Sample Apps
Here is a list of apps build with use-dark-mode
.
If you have an app you would like to include on this list, open a PR.
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!
Top Related Projects
Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
A utility-first CSS framework for rapid UI development.
⚡️ Simple, Modular & Accessible UI Components for your React Applications
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
👩🎤 CSS-in-JS library designed for high performance style composition
Build forms in React, without the tears 😭
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot