Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
reacthookstypescriptstate-management

Explicitly type useState with null initial value

Prevent type narrowing to 'null' by explicitly defining the generic type when initializing state with null.

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

Bad example

Old codetsx
1const [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>'.
5setUser({ 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

New codetsx
1interface User {
2 name: string;
3}
4
5// Explicitly define that the state can be User or null
6const [user, setUser] = useState<User | null>(null);
7
8// Works correctly
9setUser({ 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.