{"id":7844,"date":"2025-07-13T23:32:25","date_gmt":"2025-07-13T23:32:24","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7844"},"modified":"2025-07-13T23:32:25","modified_gmt":"2025-07-13T23:32:24","slug":"creating-a-theme-switcher-in-react-8","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/creating-a-theme-switcher-in-react-8\/","title":{"rendered":"Creating a Theme Switcher in React"},"content":{"rendered":"<h1>Creating a Theme Switcher in React<\/h1>\n<p>In today&#8217;s web development landscape, user experience is paramount. One effective way to enhance UX is by providing a theme switcher that allows users to toggle between light and dark modes. In this article, we&#8217;ll explore how to create a simple but efficient theme switcher using React.<\/p>\n<h2>Why Use a Theme Switcher?<\/h2>\n<p>Dark mode has gained popularity for its aesthetic appeal and potential to reduce eye strain. By giving users control over their viewing preferences, you increase engagement and user satisfaction. Implementing a theme switcher can also be a fun and interactive feature for users, making your application stand out.<\/p>\n<h2>Setting Up Your React Project<\/h2>\n<p>Let&#8217;s get started by setting up a basic React application. If you haven&#8217;t created a React app yet, you can do so using <strong>Create React App<\/strong>.<\/p>\n<pre><code>npx create-react-app theme-switcher\ncd theme-switcher\nnpm start\n<\/code><\/pre>\n<p>This command will set up a basic React application and open it in your default web browser.<\/p>\n<h2>Creating the Theme Context<\/h2>\n<p>To effectively manage our light and dark themes, we&#8217;ll create a context. This will allow any component in our app to access theme-related state and functions.<\/p>\n<pre><code>import React, { createContext, useContext, useState } from 'react';\n\n\/\/ Create a context for the theme\nconst ThemeContext = createContext();\n\n\/\/ Create a provider component\nexport const ThemeProvider = ({ children }) =&gt; {\n    const [theme, setTheme] = useState('light');\n    \n    const toggleTheme = () =&gt; {\n        setTheme(theme === 'light' ? 'dark' : 'light');\n    };\n    \n    return (\n        \n            {children}\n        \n    );\n};\n\n\/\/ Custom hook to use the theme context\nexport const useTheme = () =&gt; {\n    return useContext(ThemeContext);\n};\n<\/code><\/pre>\n<p>In this code, we created a <strong>ThemeContext<\/strong> along with a <strong>ThemeProvider<\/strong> component. The provider holds the current theme state and a method <strong>toggleTheme<\/strong> to switch between light and dark modes.<\/p>\n<h2>Implementing the Theme Switcher<\/h2>\n<p>Next, let&#8217;s create a simple button that will allow us to switch themes. We&#8217;ll use the custom hook <strong>useTheme<\/strong> that we created earlier.<\/p>\n<pre><code>import React from 'react';\nimport { useTheme } from '.\/ThemeContext';\n\nconst ThemeSwitcher = () =&gt; {\n    const { theme, toggleTheme } = useTheme();\n    \n    return (\n        <button>\n            Switch to {theme === 'light' ? 'Dark' : 'Light'} Mode\n        <\/button>\n    );\n};\n\nexport default ThemeSwitcher;\n<\/code><\/pre>\n<p>This component uses the <strong>toggleTheme<\/strong> function when the button is clicked. It also updates the button text based on the current theme.<\/p>\n<h2>Applying Styles Based on the Theme<\/h2>\n<p>Now, we need to apply different styles based on the selected theme. To illustrate this, we\u2019ll create a simple layout with some basic styles.<\/p>\n<pre><code>import React from 'react';\nimport { ThemeProvider } from '.\/ThemeContext';\nimport ThemeSwitcher from '.\/ThemeSwitcher';\nimport '.\/App.css';\n\nconst App = () =&gt; {\n    return (\n        \n            <div>\n                \n                <div>\n                    <h1>Hello, React!<\/h1>\n                    <p>This is your theme switcher example.<\/p>\n                <\/div>\n            <\/div>\n        \n    );\n};\n\nexport default App;\n<\/code><\/pre>\n<p>Now let&#8217;s create the CSS styles for light and dark themes. You can use CSS variables to switch styles easily.<\/p>\n<pre><code>:root {\n    --background-color: white;\n    --text-color: black;\n}\n\n.dark {\n    --background-color: black;\n    --text-color: white;\n}\n\n.App {\n    background-color: var(--background-color);\n    color: var(--text-color);\n    height: 100vh;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n}\n\nbutton {\n    padding: 10px 20px;\n    margin: 20px;\n    border: none;\n    cursor: pointer;\n}\n<\/code><\/pre>\n<p>Now we can dynamically apply the <strong>dark<\/strong> class based on the current theme state. Modify the <strong>App<\/strong> component to provide this functionality.<\/p>\n<pre><code>const App = () =&gt; {\n    const { theme } = useTheme();\n    \n    return (\n        \n            <div>\n                \n                <div>\n                    <h1>Hello, React!<\/h1>\n                    <p>This is your theme switcher example.<\/p>\n                <\/div>\n            <\/div>\n        \n    );\n};\n<\/code><\/pre>\n<p>With these changes, the CSS will adjust according to the chosen theme, creating a visual distinction between light and dark modes.<\/p>\n<h2>Persisting the Theme Selection<\/h2>\n<p>To improve the user experience further, we can save the user&#8217;s theme preference in <strong>localStorage<\/strong>. This way, when the user revisits the application, their preferred theme will be applied automatically.<\/p>\n<pre><code>const ThemeProvider = ({ children }) =&gt; {\n    const [theme, setTheme] = useState(() =&gt; {\n        return localStorage.getItem('theme') || 'light';\n    });\n    \n    const toggleTheme = () =&gt; {\n        const newTheme = theme === 'light' ? 'dark' : 'light';\n        setTheme(newTheme);\n        localStorage.setItem('theme', newTheme);\n    };\n    \n    return (\n        \n            {children}\n        \n    );\n};\n<\/code><\/pre>\n<p>This update checks <strong>localStorage<\/strong> for a saved theme preference when the component first renders. It updates the saved theme every time the user switches themes.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we created a functional theme switcher in React that allows users to toggle between light and dark modes. We implemented the context API to manage theme state, utilized a custom hook for easy accessibility, applied CSS based on the selected theme, and persisted the theme preference in <strong>localStorage<\/strong>.<\/p>\n<p>Theme switchers not only enhance user experience but also add a touch of personalization to your application. With just a few lines of code, you can make your app feel more dynamic and user-friendly.<\/p>\n<p>Feel free to extend this example by adding additional themes or customization options. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Creating a Theme Switcher in React In today&#8217;s web development landscape, user experience is paramount. One effective way to enhance UX is by providing a theme switcher that allows users to toggle between light and dark modes. In this article, we&#8217;ll explore how to create a simple but efficient theme switcher using React. Why Use<\/p>\n","protected":false},"author":101,"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-7844","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\/7844","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\/101"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7844"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7844\/revisions"}],"predecessor-version":[{"id":7845,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7844\/revisions\/7845"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7844"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7844"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7844"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}