Rules Hub
Coding Rules Library
Define explicit return types for custom hooks
Always define and export an explicit interface for custom hook return values using the `[HookName]Payload` naming convention.
Bad example
| 1 | export function useUserProfile(userId: string) { |
| 2 | const [user, setUser] = useState<User | null>(null); |
| 3 | const [loading, setLoading] = useState(true); |
| 4 |
|
| 5 | // Implicit return type inferred by TypeScript |
| 6 | return { user, loading }; |
| 7 | } |
Explanation (EN)
Relying on type inference for the return value makes the API contract unclear. Changes to the internal logic might accidentally change the return type, causing issues for consumers.
Objašnjenje (HR)
Oslanjanje na inferenciju tipova za povratnu vrijednost čini API ugovor nejasnim. Promjene u internoj logici mogu slučajno promijeniti povratni tip, uzrokujući probleme komponentama koje koriste hook.
Good example
| 1 | export interface UseUserProfilePayload { |
| 2 | user: User | null; |
| 3 | loading: boolean; |
| 4 | } |
| 5 |
|
| 6 | export function useUserProfile(userId: string): UseUserProfilePayload { |
| 7 | const [user, setUser] = useState<User | null>(null); |
| 8 | const [loading, setLoading] = useState(true); |
| 9 |
|
| 10 | return { user, loading }; |
| 11 | } |
Explanation (EN)
An explicit interface defines a clear contract for the hook. The `Payload` suffix follows a standard naming convention, improving readability and helping IDEs provide better autocompletion.
Objašnjenje (HR)
Eksplicitno sučelje definira jasan ugovor za hook. Sufiks `Payload` prati standardnu konvenciju imenovanja, poboljšava čitljivost i pomaže IDE-u u pružanju boljeg autocompletiona.