useDarkMode react hook

Using the Dark Mode React Hook

As someone who spends a lot of time on their computer, I understand the importance of having a comfortable and easy-to-read interface. That's where dark mode comes in.

One way to implement dark mode in a React application is by using a custom hook. A hook is a function that lets you "hook into" React state and lifecycle features from functional components.

Step 1: Create the Hook

To create a hook for dark mode, first, we need to create a new file in our project called "useDarkMode.js". In this file, we'll define our hook using the useState hook provided by React.


import { useState } from 'react';

export const useDarkMode = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);

  const toggleDarkMode = () => {
    setIsDarkMode(!isDarkMode);
  };

  return [isDarkMode, toggleDarkMode];
};

Here, we're creating a new state variable called "isDarkMode" and setting it to false by default. We're also defining a function called "toggleDarkMode" that will update the "isDarkMode" state variable when called.

Step 2: Use the Hook in our App

Now that we've created our custom hook, we can use it in any component in our app. Let's say we have a component called "Header" that we want to add dark mode functionality to.


import React from 'react';
import { useDarkMode } from './useDarkMode';

const Header = () => {
  const [isDarkMode, toggleDarkMode] = useDarkMode();

  const handleToggle = () => {
    toggleDarkMode();
  };

  return (
    <div className={isDarkMode ? 'dark-mode' : 'light-mode'}>
      <button onClick={handleToggle}>Toggle Dark Mode</button>
      <h1>My Header</h1>
    </div>
  );
};

export default Header;

Here, we're importing our custom hook and using it to set the "isDarkMode" state variable and "toggleDarkMode" function in our component. We're also defining a function called "handleToggle" that will call "toggleDarkMode" when the user clicks a button.

We're then using the "isDarkMode" state variable to conditionally render our component with a "dark-mode" or "light-mode" class. This allows us to style our component differently based on whether or not dark mode is enabled.

Multiple Ways to Implement Dark Mode

There are many ways to implement dark mode in a React application, and using a custom hook is just one of them. Other popular methods include:

  • Using the Context API to manage global state
  • Using CSS variables and media queries to toggle styles
  • Using a third-party library like react-dark-mode-toggle

Ultimately, the method you choose will depend on your specific use case and personal preferences. But by using a custom hook like the one we've created here, you can easily add dark mode functionality to any component in your app with just a few lines of code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe