Created
February 7, 2025 03:13
-
-
Save maxktz/a49b1685bc7fdaa9b421eaac9f67d117 to your computer and use it in GitHub Desktop.
Global singleton utility function for nextjs. to avoid re-initialization hot reloads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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