Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Consolidate effects with identical dependencies
Merge multiple useEffect hooks that share the same dependency array and domain concern into a single hook to improve readability and maintainability.
Bad example
| 1 | useEffect(() => { |
| 2 | setHasError(false); |
| 3 | }, [imageUrl]); |
| 4 |
|
| 5 | useEffect(() => { |
| 6 | const img = imageRef.current; |
| 7 | if (img && img.complete && img.naturalWidth === 0) { |
| 8 | setHasError(true); |
| 9 | } |
| 10 | }, [imageUrl]); |
Explanation (EN)
Using two separate effects with the exact same dependency array (`[imageUrl]`) adds unnecessary boilerplate. It separates logically related operations (resetting state and validating the image), making the code harder to scan.
Objašnjenje (HR)
Korištenje dva odvojena efekta s istim nizom ovisnosti (`[imageUrl]`) dodaje nepotreban kod. To razdvaja logički povezane operacije (resetiranje stanja i validaciju slike), čineći kod težim za pregledavanje.
Good example
| 1 | useEffect(() => { |
| 2 | setHasError(false); |
| 3 |
|
| 4 | const img = imageRef.current; |
| 5 | if (img && img.complete && img.naturalWidth === 0) { |
| 6 | setHasError(true); |
| 7 | } |
| 8 | }, [imageUrl]); |
Explanation (EN)
The logic is consolidated into a single effect. This ensures that all side effects triggered by `imageUrl` changing are grouped together, improving readability and reducing the overhead of managing multiple hooks.
Objašnjenje (HR)
Logika je objedinjena u jedan efekt. To osigurava da su svi popratni efekti pokrenuti promjenom `imageUrl` grupirani zajedno, što poboljšava čitljivost i smanjuje opterećenje upravljanja višestrukim hookovima.
Notes (EN)
Exceptions apply if the effects handle completely unrelated concerns (e.g., one for analytics and one for DOM manipulation), but generally, related logic sharing triggers should be colocated.
Bilješke (HR)
Iznimke postoje ako efekti obrađuju potpuno nepovezane stvari (npr. jedan za analitiku, a drugi za manipulaciju DOM-om), ali općenito, povezana logika koja dijeli iste okidače trebala bi biti na istom mjestu.