Rules Hub
Coding Rules Library
Validate dependencies inside useEffect
Always add guard clauses inside useEffect to check if required dependencies exist before performing expensive operations like data fetching.
Bad example
| 1 | useEffect(() => { |
| 2 | // Triggers a network request even if userId is undefined, null, or empty |
| 3 | fetch(`/api/users/${userId}`) |
| 4 | .then((res) => res.json()) |
| 5 | .then(setUser); |
| 6 | }, [userId]); |
Explanation (EN)
The effect runs immediately when the component mounts or `userId` changes, even if `userId` is missing. This results in unnecessary network requests (e.g., fetching `/api/users/undefined`) and potential 404 errors.
Objašnjenje (HR)
Efekt se pokreće odmah pri montiranju komponente ili promjeni `userId`, čak i ako `userId` nedostaje. To rezultira nepotrebnim mrežnim zahtjevima (npr. dohvaćanje `/api/users/undefined`) i potencijalnim 404 pogreškama.
Good example
| 1 | useEffect(() => { |
| 2 | // Guard clause prevents execution if dependencies are invalid |
| 3 | if (!userId) return; |
| 4 |
|
| 5 | fetch(`/api/users/${userId}`) |
| 6 | .then((res) => res.json()) |
| 7 | .then(setUser) |
| 8 | .catch(console.error); |
| 9 | }, [userId]); |
Explanation (EN)
A guard clause checks if `userId` is valid before proceeding. If it is missing, the function returns early, preventing the wasteful network call and ensuring the API is only hit with valid data.
Objašnjenje (HR)
Zaštitna klauzula provjerava je li `userId` valjan prije nastavka. Ako nedostaje, funkcija se rano vraća, sprječavajući nepotreban mrežni poziv i osiguravajući da se API poziva samo s ispravnim podacima.