Course contentsShow
← JavaScript
Lesson 1432 of 2,72331. ModulesFree lesson

Shared Module State

Why all imports of the same module reference the same instance and share state.

Shared Module State

You'll learn: How all imports of the same module reference the same instance and share any state stored within it.

The Core Idea

When you import a module multiple times across different files, JavaScript doesn't create separate copies—every import points to the same module instance. This means if the module contains variables, objects, or other state, that state is shared across all parts of your application that import it.

Think of a module like a single office whiteboard. Everyone who walks into that office sees the same whiteboard with the same writing on it. If one person changes what's written, everyone else sees that change immediately.

How It Works

// counter.js
let count = 0;

export function increment() {
  count++;
}

export function getCount() {
  return count;
}
// fileA.js
import { increment, getCount } from './counter.js';

increment();
console.log(getCount()); // 1
// fileB.js
import { getCount } from './counter.js';

console.log(getCount()); // 1 (sees the change from fileA!)

Even though fileA.js and fileB.js import separately, they share the same count variable inside counter.js. Changes made by one are visible to all.

Practical Implications

This behavior enables patterns like singleton services, shared configuration, or global caches. However, it also means you must be careful about unintended side effects—modifying module state can affect seemingly unrelated parts of your application.

Key Takeaway: All imports of a module share the same instance and state—modules act as natural singletons in JavaScript.