Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: general
singletonhmrclean-codeperformancearchitecture

Prefer remember utility for global singletons

Use a dedicated utility to persist singleton instances across module reloads instead of manual globalThis assignments.

PR: Feat/FCK-2245 - Cache Bellsheep and profile loaders with TanStack Query #343Created: Dec 10, 2025

Bad example

Old codets
1import { QueryClient } from '@tanstack/react-query';
2
3let queryClient: QueryClient;
4
5declare global {
6 var __QUERY_CLIENT__: QueryClient | undefined;
7}
8
9// Verbose manual singleton pattern to handle HMR
10if (process.env.NODE_ENV === 'production') {
11 queryClient = new QueryClient();
12} else {
13 if (!globalThis.__QUERY_CLIENT__) {
14 globalThis.__QUERY_CLIENT__ = new QueryClient();
15 }
16 queryClient = globalThis.__QUERY_CLIENT__;
17}
18
19export { queryClient };

Explanation (EN)

Manually assigning properties to `globalThis` to preserve instances across hot reloads is verbose, error-prone, and clutters the global namespace with custom property names.

Objašnjenje (HR)

Ručno dodjeljivanje svojstava na `globalThis` za očuvanje instanci tijekom 'hot reloads' je opširno, podložno greškama i zatrpava globalni prostor imena prilagođenim nazivima.

Good example

New codets
1import { remember } from '@epic-web/remember';
2import { QueryClient } from '@tanstack/react-query';
3
4// Clean, declarative singleton creation that survives HMR
5export const queryClient = remember('query-client', () => {
6 return new QueryClient({
7 defaultOptions: {
8 queries: {
9 staleTime: 60_000,
10 },
11 },
12 });
13});

Explanation (EN)

Using a utility like `remember` abstracts the complexity of persisting instances across module reloads. It ensures a single instance is created and reused while keeping the code concise and readable.

Objašnjenje (HR)

Korištenje alata poput `remember` apstrahira složenost očuvanja instanci kroz ponovno učitavanje modula. Osigurava kreiranje i ponovno korištenje jedne instance dok kod ostaje sažet i čitljiv.

Notes (EN)

This pattern is essential for database connections (Prisma), query clients, or any heavy object that should not be re-initialized during development HMR cycles.

Bilješke (HR)

Ovaj uzorak je ključan za konekcije na bazu podataka (Prisma), klijente za upite ili bilo koji 'teški' objekt koji se ne bi trebao ponovno inicijalizirati tijekom HMR ciklusa u razvoju.