DEV Community

Cover image for How to implement dark mode in react js with custom hook.
GihanRangana
GihanRangana

Posted on

How to implement dark mode in react js with custom hook.

Discover how to effortlessly add dark mode functionality to your React JS app using the useDarkMode hook and SCSS in our step-by-step guide for 2023. Elevate your user experience by following along with our comprehensive tutorial, designed for developers of all levels. With clear instructions and practical examples, you'll learn how to integrate the useDarkMode hook and utilize SCSS to create a visually appealing and dynamic dark mode feature. Enhance your coding skills and take your React applications to the next level by implementing this sought-after user interface enhancement.


yarn add -D sass
Enter fullscreen mode Exit fullscreen mode

useDarkMode Hook

import { useEffect, useState } from 'react';

const useDarkMode = () => {
    const [enabled, setEnabled] = useState(false);

    const body = document.body;

    useEffect(() => {

        body.setAttribute('theme', `${enabled ? 'dark' : 'light'}`);

    }, [enabled]);

    useEffect(() => {
        const isDarkMode = window.matchMedia(
            '(prefers-color-scheme: dark)'
        ).matches;
        const isLightMode = window.matchMedia(
            '(prefers-color-scheme: light)'
        ).matches;

        if (isDarkMode) setEnabled(true);
        if (isLightMode) setEnabled(false);
    }, []);

    return { enabled, setEnabled };
};

export default useDarkMode;
Enter fullscreen mode Exit fullscreen mode

Source Code: https://github.com/TheCodersLife/react-useDarkMode-hook

Top comments (0)