How to utilize React Context for theme management

React Context is a feature in React that allows for the efficient sharing of data across components without manually passing props through each level of the component tree. There are many applications of React Context. In this post, we are going to see one of the most simple use cases of React Context. That is React Context for theme management. If you stumble upon this post from nowhere :), first check my post on the fundamentals of React Context first.

What is theme management?

When referring to “theme management” with React Context, it typically means managing the visual appearance and styling of a React application using a theme-based approach. React Context can create a theme management system where the theme-related data, such as colors, fonts, and styles, is stored in a context and made accessible to the components throughout the application.

How to use React Context for theme management

By using React Context for theme management, you can dynamically change the theme of your application, allowing users to switch between different visual styles or customize the appearance according to their preferences. The context provider would hold the current theme data, and the components can consume this context to apply the appropriate styles and visual elements based on the selected theme.

This approach provides a centralized and efficient way to manage theme-related data and ensures consistent styling across the application. It eliminates the need to pass theme-related props manually to each component and simplifies the process of theming and customization.

React Context: Theme management demo project

We are going to develop a simple app to demonstrate how you can use context for theme management. You may have seen on many websites there is a button to toggle between night mode and day mode reading. 

When toggle between day mode and night mode, the application changes its styles dynamically. Let’s say they are a “light” version of the theme and a “dark” version theme. The “light” theme uses different sets of colors, fonts, and styles than the “dark” version. We can use React Context to toggle between these two versions.

  1. Create a React app with vite.js or create-react-app.( I am using vite.js )
  2. Create a folder called context  in the src folder (src folder is the default folder created with vite.js/ create-react-app )
  3. Create themeContext.jsx in the context folder, and add the following code
import React from 'react';
const themeContext = React.createContext([])
export default themeContext;
  1. Add another file named themeProvider.jsx in the context folder, and add the code below
import React, { useState }   from 'react';
import ThemeContext from './themeContext';

export default function ThemeProvider ({ children }){ 
 

    const [theme, setTheme] = useState('light'); // Initial theme state
  
    // Function to toggle the theme
    const toggleTheme = () => {
      setTheme(theme === 'light' ? 'dark' : 'light');
    };
  
    // Create the context value
    const contextValue = {
      theme,
      toggleTheme,
    };
  
    return(
        <ThemeContext.Provider value={contextValue}>
            { children }
        </ThemeContext.Provider>
    );
  };
  1. Add another folder called components  in the src folder
  2. Create a file named themeToggler.jsx in this folder. Add the following code

import { useContext} from "react";
import themeContext from "../context/themeContext";
import "./themeToggler.css"

export default function ThemeToggler(){
    const { theme, toggleTheme } = useContext(themeContext);
    return (
      <div  className={`theme-${theme} themeToggleWrapper`}>
        <button onClick={toggleTheme} className="toggleButton">
            { theme === 'light' ? "Day mode" : "Night mode" }
        </button>
        <section className="contentWrapper">
          <h1>THIS IS THE SOME SAMEPLE TEXT</h1><br/>
          <p>Click the button on the top right corner</p>
          </section>
      </div>
    );
  };
  1. As you can notice in the above code, there is a CSS file named themeToggler.css. We have not created it. This is the file that holds most of the styles related to our themes. Create this CSS file inside the components folder. Now, you should have two files in this folder.
.themeToggleWrapper {
  height: 100vh;
  width: 99vw;  
  text-align: right;
}

.toggleButton{
  margin-right: 10%;
  padding-top: 10px;
}

.contentWrapper{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: inherit;
}

.theme-light {
  color: rgb(20, 20, 20);
  background-color: rgb(206, 221, 198);
}

.theme-dark {
  color: rgb(240, 240, 185);
  background-color:rgb(20, 20, 20);
}

Note: You can also remove any extra styles in App.css. if you wish to.

  1. Start your app with npm run dev if you create the project with vite.js or npm start if you create your project with create-react-app

Let’s make the demo app more appealing

At the moment the toggle button does not look very appealing. We will modify the themeToggler.jsx.

  1. Create a folder called images inside the src folder
  2. Download the following images, and add them to the images folder. You can download these images from my GitHub. Please, check the Resource section at the end of the post.
React Context:: crescent
React Context: sun
  1. In the themeToggler.jsx file , add the following import statements
import sun from '../images/sun.png';
import cresent from '../images/crescent.png';
  1. And add the following constants inside of the functional component ( ThemeToggler ).
const nightButton = <img width="45px" height="45px" src={ cresent } alt="crescent" />;
const dayButton = <img width="55px" height="55px" src={ sun } alt="sun" />;
  1. finally, remove the <button> tags and replace them with the following code snippet.
<div  onClick={toggleTheme} className="toggleButton">
          { theme === 'light' ? nightButton : dayButton }       
</div>

Wrapping up

This is a small demo project. But, you have the potential to develop this app into a React Website. Add more styles to the themes and more functionality to the app. Experiment with how you can use React Context in other ways as well.

Resources

You can download the full code on GitHub

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top