DEV Community

padmajothi Athimoolam
padmajothi Athimoolam

Posted on

What is the Singleton Pattern?

What is the Singleton Pattern?

The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. The pattern is often used for managing resources like API clients, caching, or configuration that needs to be shared across various parts of the application.

In the context of React, we usually want to implement a singleton for:

  • Global state management (e.g., settings, themes).
  • API client or data management (e.g., fetching data, caching).
  • Logging or analytics service that needs to track events consistently.

How to Implement a Singleton Pattern in React

Example: Singleton for Managing Theme (Dark Mode Toggle)

Let's say you have a website that allows users to toggle between a light and dark theme. The Singleton design pattern can help manage the theme preference across the app to ensure that the same instance of the theme is applied everywhere.

1. Create the Singleton Class for Theme Management
This class will handle getting and setting the theme, and ensure there's only one instance used throughout the app.

// themeManager.js

class ThemeManager {
    constructor() {
        if(ThemeManager.instance) {
            this.theme = localStorage.getItem('theme') || 'light';
            ThemeManager.instance = this;
        }

        return ThemeManager.instance;
    }

    setTheme(newTheme) {
        this.theme = newTheme;
        localStorage.setItem('theme', newTheme);
    }

    getTheme() {
        return this.theme
    }
 }

 const themeManager = new ThemeManager(); // Create an instance
 export default themeManager; // Export the instance

Enter fullscreen mode Exit fullscreen mode

2. Using the Singleton in Your React App
Now, you can use this ThemeManager Singleton in your React components to apply and toggle the theme.

App.js

import { useEffect, useState } from 'react';
import themeManager from './themeManager';
import './app.css';

const App = () => {
  const [theme, setTheme ] = useState(themeManager.getTheme());

  useEffect(() => {
    document.body.className = theme;
  }, [theme]);

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

  return (
    <div>
      <h1>SingleTone pattern with Theme Manager</h1>
      <button onClick={toggleTheme}> Toggle to { theme === 'light' ? 'dark' : 'light' } Mode
      </button>     
    </div>
  )
}
export default App;

Enter fullscreen mode Exit fullscreen mode

3. Apply the Styles for Themes
Now you can define some CSS to switch between light and dark themes.

/* styles.css */
body.light {
  background-color: white;
  color: black;
}

body.dark {
  background-color: black;
  color: white;
}

Enter fullscreen mode Exit fullscreen mode
  • The Singleton (themeManager) ensures there’s only one instance of the theme across the entire application.
  • When the user toggles the theme, it’s updated both in localStorage (so it persists on page reloads) and in the Singleton instance.
  • The React component (in this case, App.js) listens for theme changes, and any other component can also access the same Singleton to get or update the theme.

Benefits of Using Singleton Here:

_Global State Consistency: _The theme state is consistent throughout the app, and any component can access or modify it.

Persistent Theme: By using localStorage, the theme persists across page reloads, and you ensure the same theme is used after the app is restarted.

_Single Source of Truth: _The Singleton provides a single point of truth for the theme, ensuring that no other part of the app creates its own instance of the theme or overrides the global theme state.

Check out my project on Singleton Theme manager

Top comments (0)