SoFunction
Updated on 2025-04-14

Front-end implementation of global theme switching function example code

To switch global themes can be achieved through React Hook and Context. This article will explain how to use itReact HookandContextTo realize the switching function of global themes.

What is a React Hook?

Hook in React is a new feature that allows the use of React's state, side effects, and other features in function components. Hook enables function components to handle functions that were previously implemented by class components, greatly simplifying code and improving readability and maintainability.

Hook was introduced in React 16.8, mainly to enable developers to better manage state and side effects in function components without writing complex class components. The most common hooks are:useStateuseEffectuseMemoanduseContextetc. In this article we will use theuseContext

What is a Context?

In React, Context is a mechanism for passing data across component trees, which allows us to avoid the problem of passing props layer by layer. Context allows you to access some shared data in deeply nested components without passing through props at each layer. Therefore, it is suitable for switching themes.

Specific implementation method

1. Create a Context object using ()

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

// Create a Context object with the default value of 'light'const ThemeContext = createContext('light');

A Context object has two main components:

  • Provider: Components used to provide data, usually wrapped around the root component of the application or components that need to share data.
  • Consumer: Component used to consume data, usually obtaining data through useContext or .

2. Use Provider to pass data

Next, you need to create a ThemeProvider component to store the current theme into the Context and provide a way to switch the theme. You can use the useState Hook to store the current topic, and useCallback Hook to create a way to switch topics.

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

// Create the ThemeContext objectexport const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');  // The initial theme is light  const toggleTheme = useCallback(() => {
    // Switch theme    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
  }, []);

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

Finally, we use Provider to pass the current topic and the method of switching topics to all child components.

3. Use ThemeProvider

Now we can use ThemeProvider in the App component to implement global theme switching. We can wrap all the child components in the ThemeProvider and pass the current theme to them:

import React from 'react';
import { ThemeProvider } from './ThemeProvider';
import { Header } from './Header';
import { Main } from './Main';
import { Footer } from './Footer';

export const App = () => {
  return (
    <ThemeProvider>
      <Header />
      <Main />
      <Footer />
    </ThemeProvider>
  );
};

In the App component, we wrap all the child components with ThemeProvider and pass the current theme to them.

4. Get the topic

In the child component, we can use Consumer to get the current topic:

import React from 'react';
import { ThemeContext } from './ThemeProvider';

export const Header = () => {
  return (
    <>
      {({ theme, toggleTheme }) => (
        <header className={`header ${theme}`}>
          <h1>My App</h1>
          <button onClick={toggleTheme}>Toggle Theme</button>
        </header>
      )}
    </>
  );
};

In this example:

is a component provided by React for accessing context. Its child element is a function, which receives a value parameter, and this value is the value we provide through ThemeProvider.

In value, we can deconstruct theme and toggleTheme and then use it in the component.

You can also use useContext to get the theme:

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';

export const Header = () => {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <header className={`header ${theme}`}>
      <h1>My App</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </header>
  );
};

In the subcomponent, we passuseContext(ThemeContext)How to get the current topic and switch topics. In the Header component, we bind toggleTheme to button click event so that users can switch themes.

Advantages and disadvantages of useContext and Consumer:

Compared to useContext, the Consumer syntax appears verbose and nested, especially when multiple context values ​​are required. This problem will be more obvious in complex applications.
But if in a class component, Consumer is the only way to get context values. The useContext hook cannot be used in class components, but the context can be accessed through the Consumer. useContext is more concise and easy to understand, so it is recommended to use useContext in function components.

Summarize

This article describes how to use React Hook and Context to implement global theme switching. We first create a Context object
Provide the Context value, then create a ThemeProvider component, store the current theme in the Context, and provide a way to switch the theme. Finally, use Consumer or useContext in the required component to access the value in the Context. In this way, we implement global theme switching.

This is the article about the front-end realization of global theme switching function. For more related front-end global theme switching content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!