Theme Toggler with React and Context API

Hey people welcome to the blog, i am yashvant and in this blog we gonna see how we can make theme toggler for react website, so let's get started.

Note:- I assumed that you have basic understanding of react.


Create React Project with below command

npx create-react-app theme-toggler

After project has been made write

cd theme-toggler and write npm start to start the project

now open it in any editor like sublime,vscode or atom. I am using vs code.

now in the src folder create one folder and give it name store.

after creating a folder create one file and name it theme-context.js or anything.

In theme context js write below code

import { createContext, useEffect, useState } from "react";

const ThemeContext = createContext({
    theme: "light",
    toggle: () => {},

export const ThemeProvider = props => {
    const prevTheme = localStorage.getItem("theme");
    const [theme, setTheme] = useState(prevTheme);
    useEffect(() => {
    }, [theme]);

    const toggleTheme = () => {
        if (theme === "light") {
            localStorage.setItem("theme", theme);
        } else {
            localStorage.setItem("theme", theme);
    const contextValue = {
        theme: theme,
        toggle: toggleTheme,
    return (
        <ThemeContext.Provider value={contextValue}>

export default ThemeContext;

Go to index.js and write following code

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { ThemeProvider } from "./store/theme-context";
                <App />

We have to import themeprovider to provide context in our app

go to the App.js

import "./App.css";
import ThemeContext from "./store/theme-context";
import { useContext } from "react";

function App() {
    const context = useContext(ThemeContext);
    localStorage.setItem("theme", context.theme);

    const toggleThemeHandler = () => {
    return (
        <div className="App" data-theme={context.theme}>
                    className={`themetoggler ${toggleThemeHandler }`}
                    <span role="img" aria-label="switch theme">
                        {props.theme === "dark" ? "🌞" : "🔅"}

export default App;

For theme styling create go to App.css file and write this code.

[data-theme="light"] { --text-color: black; --background-color: white; }

[data-theme="dark"] { --text-color: #fcfcfc; --background-color: #1d1c1c; }

.App { color: var(--text-color); background-color: var(--background-color); }

that's it, run it and you will see the theme toggler.

Thanks for the Reading, follow me for more easy tutorials

No Comments Yet