Skip to content

Instantly share code, notes, and snippets.

@maxktz
Created February 7, 2025 03:13
Show Gist options
  • Save maxktz/a49b1685bc7fdaa9b421eaac9f67d117 to your computer and use it in GitHub Desktop.
Save maxktz/a49b1685bc7fdaa9b421eaac9f67d117 to your computer and use it in GitHub Desktop.
Global singleton utility function for nextjs. to avoid re-initialization hot reloads
export function globalSingleton<T>(key: string, createInstance: () => T): T {
const globalStore = globalThis as unknown as Record<string, T | undefined>;
if (!globalStore[key]) {
globalStore[key] = createInstance();
}
return globalStore[key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment