{"id":6262,"date":"2025-05-31T05:32:40","date_gmt":"2025-05-31T05:32:39","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6262"},"modified":"2025-05-31T05:32:40","modified_gmt":"2025-05-31T05:32:39","slug":"dark-mode-in-react-the-easy-way-6","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/dark-mode-in-react-the-easy-way-6\/","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>As developers, we are always on the lookout for ways to enhance user experience, and one increasingly popular feature is dark mode. Many users prefer dark mode not only for aesthetics but also for reducing eye strain and conserving battery life on OLED screens. In this article, we will explore how to easily implement dark mode in a React application.<\/p>\n<h2>What is Dark Mode?<\/h2>\n<p>Dark mode, also known as night mode, is a color scheme that uses a dark background with lighter text. This mode can help reduce blue light exposure and make reading content easier in low-light environments. It&#8217;s available across various platforms and applications, from operating systems to individual applications like web apps and mobile apps.<\/p>\n<h2>Benefits of Dark Mode<\/h2>\n<ul>\n<li><strong>Less Eye Strain:<\/strong> Many users find dark backgrounds easier to look at, especially in dim lighting.<\/li>\n<li><strong>Battery Efficiency:<\/strong> On OLED screens, dark pixels consume less power.<\/li>\n<li><strong>Aesthetic Appeal:<\/strong> Dark mode has become a design trend that many users appreciate.<\/li>\n<\/ul>\n<h2>Setting Up Your React Application<\/h2>\n<p>Before we dive into implementing dark mode, let&#8217;s set up a basic React application. If you haven&#8217;t already, you can create a new React app using Create React App:<\/p>\n<pre><code>npx create-react-app dark-mode-example<\/code><\/pre>\n<p>Once your app is created, navigate into the project directory:<\/p>\n<pre><code>cd dark-mode-example<\/code><\/pre>\n<h2>Adding State Management with Context API<\/h2>\n<p>To manage dark mode state effectively, we can leverage React&#8217;s Context API. This will allow us to easily share the dark mode state across the component tree without prop drilling. First, let\u2019s create a Context for our dark mode.<\/p>\n<h3>Creating the Context<\/h3>\n<p>Create a new file named <strong>ThemeContext.js<\/strong> in the <strong>src<\/strong> directory:<\/p>\n<pre><code>import React, { createContext, useState, useContext } from 'react';\n\nconst ThemeContext = createContext();\n\nexport const ThemeProvider = ({ children }) =&gt; {\n    const [darkMode, setDarkMode] = useState(false);\n\n    return (\n        \n            {children}\n        \n    );\n};\n\nexport const useTheme = () =&gt; useContext(ThemeContext);\n<\/code><\/pre>\n<p>This code sets up a context with a state variable for dark mode and a function to toggle it.<\/p>\n<h3>Wrapping Your Application with the Provider<\/h3>\n<p>Next, let&#8217;s wrap our entire application in the <strong>ThemeProvider<\/strong>. Open <strong>src\/index.js<\/strong> and modify it as follows:<\/p>\n<pre><code>import React from 'react';\nimport ReactDOM from 'react-dom';\nimport '.\/index.css';\nimport App from '.\/App';\nimport { ThemeProvider } from '.\/ThemeContext';\n\nReactDOM.render(\n    \n        \n    ,\n    document.getElementById('root')\n);\n<\/code><\/pre>\n<h2>Creating the Dark Mode Toggle<\/h2>\n<p>Now that we have our context set up, it\u2019s time to create a toggle button for dark mode. Let\u2019s create a simple component named <strong>ThemeToggle.js<\/strong>.<\/p>\n<pre><code>import React from 'react';\nimport { useTheme } from '.\/ThemeContext';\n\nconst ThemeToggle = () =&gt; {\n    const { darkMode, setDarkMode } = useTheme();\n\n    return (\n        <button> setDarkMode(!darkMode)}&gt;\n            Switch to {darkMode ? 'Light' : 'Dark'} Mode\n        <\/button>\n    );\n};\n\nexport default ThemeToggle;\n<\/code><\/pre>\n<p>This button will toggle the dark mode state when clicked.<\/p>\n<h3>Using the Button in the Main App<\/h3>\n<p>In your <strong>App.js<\/strong> file, you can now import and use the <strong>ThemeToggle<\/strong> component:<\/p>\n<pre><code>import React from 'react';\nimport '.\/App.css';\nimport ThemeToggle from '.\/ThemeToggle';\nimport { useTheme } from '.\/ThemeContext';\n\nconst App = () =&gt; {\n    const { darkMode } = useTheme();\n\n    return (\n        <div>\n            <h1>Hello, World!<\/h1>\n            \n        <\/div>\n    );\n};\n\nexport default App;\n<\/code><\/pre>\n<h2>Styling for Dark Mode<\/h2>\n<p>Next, we need to add some styles to our application. Open <strong>src\/App.css<\/strong> and add styles for both light and dark modes:<\/p>\n<pre><code>body {\n    margin: 0;\n    font-family: Arial, sans-serif;\n}\n\n.App {\n    text-align: center;\n    padding: 20px;\n    background-color: white;\n    color: black;\n    transition: background-color 0.3s ease, color 0.3s ease;\n}\n\n.App.dark-mode {\n    background-color: #121212;\n    color: #ffffff;\n}\n<\/code><\/pre>\n<p>With this, our application will respond to the state of dark mode with smooth transitions between styles!<\/p>\n<h2>Persisting User&#8217;s Preference<\/h2>\n<p>It\u2019s essential to save users&#8217; preferences across sessions. For this, we can use the <strong>localStorage<\/strong>. Update the <strong>ThemeProvider<\/strong> to read from and write to localStorage:<\/p>\n<pre><code>import React, { createContext, useState, useContext, useEffect } from 'react';\n\nconst ThemeContext = createContext();\n\nexport const ThemeProvider = ({ children }) =&gt; {\n    const [darkMode, setDarkMode] = useState(() =&gt; {\n        const savedMode = localStorage.getItem('darkMode');\n        return savedMode === 'true' || false;\n    });\n\n    useEffect(() =&gt; {\n        localStorage.setItem('darkMode', darkMode);\n    }, [darkMode]);\n\n    return (\n        \n            {children}\n        \n    );\n};\n\nexport const useTheme = () =&gt; useContext(ThemeContext);\n<\/code><\/pre>\n<h2>Enhancing Dark Mode with CSS Variables<\/h2>\n<p>For more flexibility and ease of use, CSS variables can be beneficial when it comes to theming. Let\u2019s modify our styles to use CSS variables.<\/p>\n<pre><code>:root {\n    --background-light: white;\n    --background-dark: #121212;\n    --text-light: black;\n    --text-dark: #ffffff;\n}\n\n.App {\n    background-color: var(--background-light);\n    color: var(--text-light);\n}\n\n.App.dark-mode {\n    background-color: var(--background-dark);\n    color: var(--text-dark);\n}\n<\/code><\/pre>\n<p>This approach allows for easier theming, especially if you introduce more themed elements in the future.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we\u2019ve learned how to implement dark mode in a React application using the Context API and localStorage for state management. By providing users with the ability to switch to dark mode, we enhance their experience and cater to their preferences. This is just the beginning; you can expand on this by adding further customization and more complex theming solutions.<\/p>\n<p>As always, happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Implementing Dark Mode in React: A Step-by-Step Guide As developers, we are always on the lookout for ways to enhance user experience, and one increasingly popular feature is dark mode. Many users prefer dark mode not only for aesthetics but also for reducing eye strain and conserving battery life on OLED screens. In this article,<\/p>\n","protected":false},"author":81,"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-6262","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\/6262","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\/81"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6262"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6262\/revisions"}],"predecessor-version":[{"id":6263,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6262\/revisions\/6263"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6262"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6262"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6262"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}