Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
reacthooksclean-codetypescripterror-handling

Avoid defensive checks for required globals in effects

useEffect runs only in the browser, so checking for window is redundant. Avoid silently skipping logic if required globals are missing; rely on strict types or fail loudly.

PR: Feat/FCK-1623 - Adding eAvis widget to the sidebar #3643Created: Dec 8, 2025

Bad example

Old codets
1useEffect(() => {
2 // Redundant check: useEffect only runs in browser
3 // Silent failure: if window.Config is missing, this fails silently
4 if (typeof window !== 'undefined' && window.Config && window.Config.analyticsId) {
5 initAnalytics(window.Config.analyticsId);
6 }
7}, []);

Explanation (EN)

Checking 'typeof window' inside useEffect is redundant code bloat. Additionally, wrapping critical logic in defensive 'if' checks causes the feature to fail silently if the configuration is missing, hiding integration bugs.

Objašnjenje (HR)

Provjera 'typeof window' unutar useEffect-a je nepotrebna. Također, omatanje kritične logike u defenzivne 'if' provjere uzrokuje tihi neuspjeh funkcionalnosti ako konfiguracija nedostaje, čime se skrivaju bugovi u integraciji.

Good example

New codets
1useEffect(() => {
2 // Assume browser environment.
3 // Trust strict TypeScript types: if Config is required, access it directly.
4 // If it's missing at runtime, it's better to crash/log error than fail silently.
5 initAnalytics(window.Config.analyticsId);
6}, []);

Explanation (EN)

Removes the redundant environment check. It assumes that if the component is mounted, the required global configuration must exist (enforced by types), preventing silent failures and clarifying intent.

Objašnjenje (HR)

Uklanja nepotrebnu provjeru okruženja. Pretpostavlja se da, ako je komponenta montirana, obavezna globalna konfiguracija mora postojati (što osiguravaju tipovi), čime se sprječavaju tihi neuspjesi i pojašnjava namjera.

Notes (EN)

If a global property is truly optional, mark it as optional in the TypeScript interface definition (e.g., `user?: User`) instead of adding runtime checks that contradict the types.

Bilješke (HR)

Ako je globalno svojstvo stvarno opcionalno, označite ga kao opcionalno u TypeScript definiciji sučelja (npr. `user?: User`) umjesto dodavanja runtime provjera koje su u suprotnosti s tipovima.