Singleton with IIFE for state management in JavaScript
Damandeep Singh

Damandeep Singh @damandeep_singh_7c4698e97

About: Learner

Location:
New Delhi, India
Joined:
May 3, 2025

Singleton with IIFE for state management in JavaScript

Publish Date: Jun 23
2 1

Ever needed a centralized configuration manager in your JavaScript app? 🤔

In modern JavaScript apps, managing shared state or configuration often means reaching for heavy tools like Redux, Zustand, or context APIs. But what if you're working on a small utility, a framework-agnostic widget, or just need a simple global config?

This is where the Singleton pattern with an IIFE (Immediately Invoked Function Expression) comes in handy.

It offers a lightweight, zero-dependency way to encapsulate state, avoid global pollution, and keep things clean—all without introducing a full-blown state manager.

🔧 Here's how I use the Singleton + IIFE pattern:

const configManager = (() => {
  let config = {};

  return {
    set(key, value) {
      config[key] = value;
    },
    get(key) {
      return key ? config[key] : config;
    }
  };
})();

// Usage
configManager.set("theme", "dark");
configManager.set("language", "en");

console.log(configManager.get("theme"));   // "dark"
console.log(configManager.get());          
// { theme: "dark", language: "en" }
Enter fullscreen mode Exit fullscreen mode

🛠️ Practical Uses of Singleton IIFE :-

1️⃣ Small Projects or Utilities

When you're building a small app or a quick utility, full-blown state management is often unnecessary.

  • Lightweight, zero-dependency
  • Simple centralized storage for shared data or config

2️⃣ Global Configuration / Settings

Perfect for app-wide settings that don’t require reactivity:

  • 🌐 API_BASE_URL, locale, featureToggles
  • 🎨 Theme settings: dark, light
  • 🌍 Language preferences: en, fr

Just a simple, centralized store to read/write values—no state management library needed.

3️⃣ Vanilla JS or Non-Framework Environments

If you're working outside of modern UI frameworks like React or Vue (e.g., in a widget or a JavaScript library), this approach works great.

  • No React/Redux overhead
  • Keeps your footprint minimal and portable

4️⃣ Encapsulation + Immutability

Using a Singleton with an IIFE gives you:

  • 🔒 Private internal state
  • 🧪 Access only via controlled get/set methods
  • 🚫 Prevents accidental mutations

This is especially useful when you want to enforce strict, controlled state updates.

If you found this helpful, consider dropping a ❤️ or sharing with a fellow dev!

Comments 1 total

  • Karandeep Singh
    Karandeep SinghJun 24, 2025

    Insightful, using factory functions with closures, great idea...

Add comment