{"id":5379,"date":"2025-04-29T13:32:38","date_gmt":"2025-04-29T13:32:37","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=5379"},"modified":"2025-04-29T13:32:38","modified_gmt":"2025-04-29T13:32:37","slug":"dark-mode-in-react-the-easy-way","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/dark-mode-in-react-the-easy-way\/","title":{"rendered":"Dark Mode in React the Easy Way"},"content":{"rendered":"<h1>Dark Mode in React the Easy Way<\/h1>\n<p>In recent years, dark mode has surged in popularity across applications and operating systems. It not only reduces eye strain in low-light conditions but also enhances battery life for OLED screens. Implementing dark mode in React apps has never been easier, and in this article, we&#8217;ll explore a straightforward method for doing so. Whether you&#8217;re a beginner just starting with React or a seasoned developer looking to implement this feature efficiently, this guide is for you.<\/p>\n<h2>Understanding Dark Mode and Its Benefits<\/h2>\n<p>Dark mode, as the name suggests, is a user interface design that displays light text on a dark background. Here are some key benefits:<\/p>\n<ul>\n<li><strong>Reduced Eye Strain:<\/strong> Dark themes can reduce glare and make it easier on the eyes, especially in dim environments.<\/li>\n<li><strong>Battery Saving:<\/strong> On OLED and AMOLED screens, dark pixels use less power, thus extending battery life.<\/li>\n<li><strong>Enhanced Readability:<\/strong> Many users find content easier to read and comprehend in dark mode.<\/li>\n<\/ul>\n<h2>Preparing Your React Application<\/h2>\n<p>Before we implement dark mode, ensure you have a basic React application set up. We will use <strong>create-react-app<\/strong> to quickly bootstrap our application. If you haven\u2019t created one yet, you can do so with the following command:<\/p>\n<pre><code>npx create-react-app dark-mode-example<\/code><\/pre>\n<p>Once your app is ready, navigate to the project directory:<\/p>\n<pre><code>cd dark-mode-example<\/code><\/pre>\n<h2>Setting Up State Management for Dark Mode<\/h2>\n<p>We will manage the dark mode state using React&#8217;s built-in <strong>useState<\/strong> and <strong>useEffect<\/strong> hooks. Our application will remember user preferences using local storage.<\/p>\n<h3>Creating the Theme Context<\/h3>\n<p>First, let&#8217;s create a context to share the dark mode state across our components. Create a new file called <strong>ThemeContext.js<\/strong> in the <strong>src<\/strong> directory:<\/p>\n<pre><code>touch src\/ThemeContext.js<\/code><\/pre>\n<p>Now, add the following code to your <strong>ThemeContext.js<\/strong> file:<\/p>\n<pre><code>import React, { createContext, useContext, useState, useEffect } from 'react';\n\nconst ThemeContext = createContext();\n\nexport const ThemeProvider = ({ children }) =&gt; {\n    const [isDarkMode, setIsDarkMode] = useState(() =&gt; {\n        \/\/ Get the user's preference from local storage or default to false\n        return JSON.parse(localStorage.getItem('darkMode')) || false;\n    });\n\n    useEffect(() =&gt; {\n        \/\/ Save the user's preference in local storage\n        localStorage.setItem('darkMode', JSON.stringify(isDarkMode));\n        document.body.className = isDarkMode ? 'dark' : 'light';\n    }, [isDarkMode]);\n\n    const toggleTheme = () =&gt; {\n        setIsDarkMode((prevMode) =&gt; !prevMode);\n    };\n\n    return (\n        \n            {children}\n        \n    );\n};\n\nexport const useTheme = () =&gt; useContext(ThemeContext);\n<\/code><\/pre>\n<h2>Applying the Theme Context in Your Application<\/h2>\n<p>Now that we have our theme context set up, let&#8217;s integrate it into our main <strong>App.js<\/strong> file.<\/p>\n<pre><code>import React from 'react';\nimport { ThemeProvider } from '.\/ThemeContext';\nimport TodoApp from '.\/TodoApp'; \/\/ assume we will create a TodoApp component for demonstration\n\nconst App = () =&gt; {\n    return (\n        \n            \n        \n    );\n}\n\nexport default App;\n<\/code><\/pre>\n<h2>Building a Sample Component to Test Dark Mode<\/h2>\n<p>Next, we\u2019ll create a simple component to showcase the dark mode functionality. For this example, we will create a <strong>TodoApp<\/strong> component. Create a new file called <strong>TodoApp.js<\/strong> in the <strong>src<\/strong> directory:<\/p>\n<pre><code>touch src\/TodoApp.js<\/code><\/pre>\n<p>Now, add the following code to your <strong>TodoApp.js<\/strong> file:<\/p>\n<pre><code>import React from 'react';\nimport { useTheme } from '.\/ThemeContext';\n\nconst TodoApp = () =&gt; {\n    const { isDarkMode, toggleTheme } = useTheme();\n\n    return (\n        <div style=\"{{\">\n            <h1 style=\"{{\">Todo List<\/h1>\n            <button style=\"{{\">\n                Switch to {isDarkMode ? 'Light' : 'Dark'} Mode\n            <\/button>\n            <div style=\"{{\">\n                <p>{isDarkMode ? 'Dark mode is activated!' : 'Light mode is activated!'}<\/p>\n            <\/div>\n        <\/div>\n    );\n}\n\nexport default TodoApp;\n<\/code><\/pre>\n<h2>Styling the Dark Mode<\/h2>\n<p>To make it visually appealing, let&#8217;s define some basic CSS for our dark and light themes. Create a CSS file called <strong>styles.css<\/strong> in the <strong>src<\/strong> directory:<\/p>\n<pre><code>touch src\/styles.css<\/code><\/pre>\n<p>In this CSS file, add the following styles:<\/p>\n<pre><code>body.light {\n    background-color: #f0f0f0;\n    color: #333;\n}\n\nbody.dark {\n    background-color: #121212;\n    color: #ffffff;\n}\n\nh1 {\n    font-size: 2em;\n}\n\nbutton {\n    padding: 10px 20px;\n    border: none;\n    border-radius: 5px;\n    cursor: pointer;\n    background-color: #007bff;\n    color: #fff;\n}\n\nbutton:hover {\n    background-color: #0056b3;\n}\n<\/code><\/pre>\n<p>Now, don&#8217;t forget to import this CSS file in your <strong>index.js<\/strong> file:<\/p>\n<pre><code>import '.\/styles.css';<\/code><\/pre>\n<h2>Testing Your Dark Mode Implementation<\/h2>\n<p>Everything is ready! Now you can start your application using:<\/p>\n<pre><code>npm start<\/code><\/pre>\n<p>Once the app is running, you should be able to toggle between dark and light mode using the button. The styling will adapt to your chosen mode, effectively showcasing the dark mode functionality.<\/p>\n<h2>Extending Functionality with Themes<\/h2>\n<p>Now that the basic dark mode is implemented, you might want to extend its functionality by allowing users to select between multiple themes. You can create an array of theme configurations and add a dropdown to select them. This can be done by modifying the context and the TodoApp component to handle the selected theme.<\/p>\n<h3>Updating the Theme Context<\/h3>\n<pre><code>const themes = {\n    light: {\n        body: '#f0f0f0',\n        text: '#333'\n    },\n    dark: {\n        body: '#121212',\n        text: '#fff'\n    }\n};\n\nconst [theme, setTheme] = useState(themes.light);\n\nuseEffect(() =&gt; {\n    document.body.style.backgroundColor = theme.body;\n    document.body.style.color = theme.text;\n}, [theme]);\n<\/code><\/pre>\n<h3>Making the Changes in TodoApp<\/h3>\n<p>Finally, integrate a dropdown in the <strong>TodoApp<\/strong> component to change between themes.<\/p>\n<pre><code>\n setTheme(themes[e.target.value])}&gt;\n    Light Theme\n    Dark Theme\n\n<\/code><\/pre>\n<h2>Conclusion<\/h2>\n<p>Implementing dark mode in a React application can be done efficiently with the use of contexts, hooks, and some straightforward CSS. The approach we&#8217;ve discussed is flexible and can be expanded to accommodate more complex requirements. It\u2019s a valuable feature that enhances user experience by allowing customization and comfort. Now go ahead and implement this feature in your projects to add an extra layer of appeal!<\/p>\n<p>For more content like this, be sure to follow our blog or subscribe for updates on the latest tips and tricks in web development!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Dark Mode in React the Easy Way In recent years, dark mode has surged in popularity across applications and operating systems. It not only reduces eye strain in low-light conditions but also enhances battery life for OLED screens. Implementing dark mode in React apps has never been easier, and in this article, we&#8217;ll explore a<\/p>\n","protected":false},"author":82,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[398],"tags":[224],"class_list":{"0":"post-5379","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-react","7":"tag-react"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5379","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/82"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=5379"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5379\/revisions"}],"predecessor-version":[{"id":5380,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5379\/revisions\/5380"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=5379"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=5379"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=5379"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}