- Daishi Kato's Read the Code
- Posts
- Detecting Dual Module Issues in Jotai
Detecting Dual Module Issues in Jotai
Mixing CJS and ESM Can Cause the Issue
Hi,
In this post, I will share a small code snippet in Jotai. Before diving into the code, let me briefly recap an issue known as the dual module issue or dual package hazard. When we define a variable in a module, we expect it to exist as a single instance globally.
// foo-module.js
export const cache = new WeakMap();
However, in reality, multiple instances can sometimes exist. The source file can be copied for various reasons, leading to multiple cache
values coexisting in memory. One common case is when the source JS/TS code is compiled into both CJS and ESM formats. This is exactly what happens with Jotai.
This issue only arises if library users mix CJS and ESM, but it can happen unintentionally. To at least detect the situation, Jotai includes a check in development mode.
Here's the code:
Jotai source reference
globalThis.__JOTAI_DEFAULT_STORE__ ||= defaultStore;
if (globalThis.__JOTAI_DEFAULT_STORE__ !== defaultStore) {
console.warn(
'Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044',
);
}
This code stores a module variable in globalThis
and checks whether a different instance exists. If multiple instances are detected, a warning message is displayed. This doesn't solve the issue entirely, but at the very least, it alerts users that something unexpected is happening. Otherwise, debugging would be much harder.
By the way, I noticed that the code can be slightly simplified:
if ((globalThis.__JOTAI_DEFAULT_STORE__ ||= defaultStore) !== defaultStore) {
console.warn('...');
}
While this technique might not be necessary for app development, I hope it helps you understand the problem.
Happy coding.
Reply