{"id":6424,"date":"2025-06-05T11:32:40","date_gmt":"2025-06-05T11:32:39","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6424"},"modified":"2025-06-05T11:32:40","modified_gmt":"2025-06-05T11:32:39","slug":"dark-mode-in-react-the-easy-way-8","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/dark-mode-in-react-the-easy-way-8\/","title":{"rendered":"Dark Mode in React the Easy Way"},"content":{"rendered":"<h1>Implementing Dark Mode in React: A Step-by-Step Guide<\/h1>\n<p>Dark mode has gained significant traction as a user-preferred feature in modern web applications. By reducing eye strain and saving battery life on devices with OLED screens, dark mode enhances user experience. In this blog post, we will explore an easy way to implement dark mode in a React application using React&#8217;s built-in capabilities and CSS. Let\u2019s dive into creating this functionality step by step!<\/p>\n<h2>Why Implement Dark Mode?<\/h2>\n<p>Before we start coding, let\u2019s understand why dark mode is not just a trendy feature but a significant enhancement:<\/p>\n<ul>\n<li><strong>Improved Accessibility:<\/strong> Dark mode is easier on the eyes, especially in low-light environments.<\/li>\n<li><strong>Battery Saving:<\/strong> On OLED displays, displaying black pixels consumes less power.<\/li>\n<li><strong>Custom User Experience:<\/strong> It allows users to choose their preferred viewing experience, enhancing overall satisfaction.<\/li>\n<\/ul>\n<h2>Setting Up Your React Project<\/h2>\n<p>If you don&#8217;t have an existing React project, you can quickly set one up using Create React App. Open your terminal and run the following command:<\/p>\n<pre><code>npx create-react-app dark-mode-app<\/code><\/pre>\n<p>After the setup is complete, navigate to the project folder:<\/p>\n<pre><code>cd dark-mode-app<\/code><\/pre>\n<h2>Creating a Dark Mode Toggle<\/h2>\n<p>We will create a simple toggle button to switch between light and dark modes. The toggle state will be managed using React&#8217;s state management system.<\/p>\n<h3>Step 1: Setting Up State Management<\/h3>\n<p>First, we need to set up the state for our dark mode preference. Open <code>src\/App.js<\/code> and modify it as follows:<\/p>\n<pre><code>import React, { useState, useEffect } from 'react';\nimport '.\/App.css';\n\nfunction App() {\n    const [darkMode, setDarkMode] = useState(false);\n\n    const toggleDarkMode = () =&gt; {\n        setDarkMode(prevMode =&gt; !prevMode);\n    };\n\n    useEffect(() =&gt; {\n        if (darkMode) {\n            document.body.classList.add('dark-mode');\n        } else {\n            document.body.classList.remove('dark-mode');\n        }\n    }, [darkMode]);\n\n    return (\n        <div>\n            <h1>{darkMode ? 'Dark Mode' : 'Light Mode'}<\/h1>\n            <button>\n                Toggle to {darkMode ? 'Light' : 'Dark'} Mode\n            <\/button>\n        <\/div>\n    );\n}\n\nexport default App;<\/code><\/pre>\n<p>In the code above, we defined a <code>darkMode<\/code> state that toggles between <code>true<\/code> and <code>false<\/code>. The <code>useEffect<\/code> hook updates the class of the body element accordingly.<\/p>\n<h3>Step 2: Adding CSS for Dark Mode<\/h3>\n<p>Next, you need to add the CSS styles for dark mode. Create a new file named <code>App.css<\/code> in the <code>src<\/code> directory and add the following styles:<\/p>\n<pre><code>body {\n    background-color: #ffffff;\n    color: #000000;\n    transition: all 0.3s ease;\n}\n\n.dark-mode {\n    background-color: #121212;\n    color: #ffffff;\n}\n\nbutton {\n    padding: 10px;\n    margin: 20px;\n    cursor: pointer;\n    border: none;\n    border-radius: 5px;\n    font-size: 16px;\n}\n\nbutton:hover {\n    background-color: #e0e0e0;\n}\n\n.dark-mode button:hover {\n    background-color: #3a3a3a;\n}<\/code><\/pre>\n<p>The CSS styles provide a smooth transition between light and dark modes, changing the background color and text color appropriately.<\/p>\n<h2>Persisting User Preference<\/h2>\n<p>To enhance the user experience, it\u2019s essential to retain the user\u2019s theme preference, even after refreshing the page. You can achieve this using the <code>localStorage<\/code> feature. Update the <code>useEffect<\/code> hook in your <code>App.js<\/code> file to save and retrieve the user&#8217;s preference:<\/p>\n<pre><code>useEffect(() =&gt; {\n    const savedMode = localStorage.getItem('darkMode');\n    if (savedMode) {\n        setDarkMode(savedMode === 'true');\n    }\n}, []);\n\nuseEffect(() =&gt; {\n    localStorage.setItem('darkMode', darkMode);\n    if (darkMode) {\n        document.body.classList.add('dark-mode');\n    } else {\n        document.body.classList.remove('dark-mode');\n    }\n}, [darkMode]);<\/code><\/pre>\n<h2>Responsive Design Considerations<\/h2>\n<p> When building an application, ensure that your dark mode implementation is responsive. The above implementation with buttons and text works well for general layout. However, consider your entire UI\u2014such as modals, tooltips, or cards\u2014ensuring they also adapt to dark mode styling.<\/p>\n<h3>Example of a Responsive Card Component<\/h3>\n<p>You can create a simple card component that changes based on the theme. Here\u2019s an example:<\/p>\n<pre><code>import React from 'react';\nimport '.\/Card.css'; \/\/ Assuming you create a separate CSS for Card\n\nconst Card = ({ title, description }) =&gt; {\n    return (\n        <div>\n            <h2>{title}<\/h2>\n            <p>{description}<\/p>\n        <\/div>\n    );\n};\n\nexport default Card;<\/code><\/pre>\n<p>The accompanying CSS in <code>Card.css<\/code> would look like this:<\/p>\n<pre><code>.card {\n    background-color: #f9f9f9;\n    padding: 20px;\n    border-radius: 8px;\n    transition: all 0.3s ease;\n}\n\n.dark-mode .card {\n    background-color: #2c2c2c;\n    color: white;\n}<\/code><\/pre>\n<h2>Conclusion<\/h2>\n<p>Implementing dark mode in React does not have to be complicated. By utilizing React\u2019s state management and CSS, you can create a user-friendly toggle for dark mode. Remember that maintaining user preferences enhances the experience and demonstrates users&#8217; consideration. As you continue to develop applications, consider integrating dark mode features to cater to a broader audience.<\/p>\n<p>By following the steps outlined in this guide, you should now have a fully functional dark mode in your React application. Don\u2019t forget to test your implementation across different devices to ensure a consistent user experience!<\/p>\n<p>Happy coding!<\/p>\n<h2>Additional Resources<\/h2>\n<ul>\n<li><a href=\"https:\/\/reactjs.org\/docs\/hooks-intro.html\">React Hooks Documentation<\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Window\/localStorage\">MDN Web Docs &#8211; Local Storage<\/a><\/li>\n<li><a href=\"https:\/\/akveo.github.io\/ngx-admin\/\">Template example of dark mode in custom design systems<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Implementing Dark Mode in React: A Step-by-Step Guide Dark mode has gained significant traction as a user-preferred feature in modern web applications. By reducing eye strain and saving battery life on devices with OLED screens, dark mode enhances user experience. In this blog post, we will explore an easy way to implement dark mode in<\/p>\n","protected":false},"author":88,"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":["post-6424","post","type-post","status-publish","format-standard","category-react","tag-react"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6424","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\/88"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6424"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6424\/revisions"}],"predecessor-version":[{"id":6427,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6424\/revisions\/6427"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6424"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6424"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6424"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}