Open In App

Create a Context Provider for Theming using React Hooks

In this article, we are going to build a context provider for managing the theme of a React app using React hooks. This will allow the user to switch between dark and light themes throughout the application. Centralizing the theme will give us an edge as the application will be able to efficiently propagate theme changes to all components since we will wrap our entire application with the theme context provider created.

Output Preview: Let us have a look at how the final output will look like.

2024-03-0705-36-53-ezgifcom-video-to-gif-converter

Preview Image of the Final Output

Prerequisites

Approach to Create Context Provider for Theming using React:

Steps to Create the React App:

Step 1: Create a new react app and enter into it by running the following commands

npx create-react-app theme-context
cd theme-context

Step 2: Create `ThemeContext.js` at `src` where we will build our theme provider using createContext API.

Step 3: We will build a simple div in App.js, the styling of which will be conditionally changed as the state of theme changes. Obviously, we will create a toggle button to change the state of the theme.

Folder Structure:

theme1

project structure

Example Code: Provide below are the codes for the working example of a theme provider built using useContext API and useState hook.

/* App.css */


* {
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    transition: 0.5s ease-in-out;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
// src/ThemeContext.js

import React, {
    createContext,
    useContext,
    useState
} from 'react';

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
    const [theme, setTheme] = useState('light');

    const toggleTheme = () => {
        setTheme(theme === 'light' ? 'dark' : 'light');
    };

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};

export const useTheme = () => useContext(ThemeContext);
// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ThemeProvider } from './ThemeContext';

ReactDOM.render(
    <React.StrictMode>
        <ThemeProvider>
            <App />
        </ThemeProvider>
    </React.StrictMode>,
    document.getElementById('root')
);
// src/App.js

import React from 'react';
import { useTheme } from './ThemeContext.js';
import './App.css';

const App = () => {
  const { theme, toggleTheme } = useTheme();

  return (
    <>
      <div style={{
         display: 'flex', justifyContent: 'center', 
         alignItems: 'center', width: '100%', 
         height: '100vh', 
         background: theme === 'light' ? 'lightgray' : 'black' }}>
        <div style={{ 
            display: 'flex', flexDirection: 'column',
             alignItems: 'center' }}>
          <div>
            <div onClick={() => toggleTheme()} 
            style={{
                 border: '1px solid gray', position: 'realtive',
                  width: '40px', height: '20px', 
                  background: theme === 'light' ? 'white' : 'black' }}>
              <div style={{ position: 'relative', top: '1px',
                               left: theme === 'light' ? '1px' : '21px', 
                               width: '16px', height: '16px', 
               background: theme === 'light' ? 'black' : 'white' }}>
               </div>
            </div>
          </div>
          <div style={{ 
            marginTop: '20px', 
            color: theme === 'light' ? 'black' : 'white' }}>
                @GeeksforGeeks Theme Change (Theme Context Provider)
                </div>
        </div>
      </div>
    </>
  );
};

export default App;

Start your application using the following command.

npm start

Output:

 Context Provider for Theming using React Hooks

Context Provider for Theming using React Hooks

Article Tags :