Rules Hub
Coding Rules Library
Explicitly type useState with null initial value
Prevent type narrowing to 'null' by explicitly defining the generic type when initializing state with null.
Bad example
| 1 | const [user, setUser] = useState(null); |
| 2 |
|
| 3 | // Later in code: |
| 4 | // Error: Argument of type '{ name: string }' is not assignable to parameter of type 'SetStateAction<null>'. |
| 5 | setUser({ name: 'Alice' }); |
Explanation (EN)
When `useState` is initialized with `null` without a generic type, TypeScript infers the state type as strictly `null`. This makes it impossible to update the state with actual data later, causing type errors.
Objašnjenje (HR)
Kada se `useState` inicijalizira s `null` bez generičkog tipa, TypeScript zaključuje da je tip stanja isključivo `null`. To onemogućuje kasnije ažuriranje stanja stvarnim podacima i uzrokuje greške u tipovima.
Good example
| 1 | interface User { |
| 2 | name: string; |
| 3 | } |
| 4 |
|
| 5 | // Explicitly define that the state can be User or null |
| 6 | const [user, setUser] = useState<User | null>(null); |
| 7 |
|
| 8 | // Works correctly |
| 9 | setUser({ name: 'Alice' }); |
Explanation (EN)
By explicitly providing the generic type `<User | null>`, we tell TypeScript that the state is allowed to hold either the initial `null` value or a `User` object, enabling safe state updates.
Objašnjenje (HR)
Eksplicitnim navođenjem generičkog tipa `<User | null>`, govorimo TypeScriptu da stanje može sadržavati početnu `null` vrijednost ili objekt tipa `User`, što omogućuje sigurno ažuriranje stanja.