useState with Complex Types and Null
You'll learn how to handle optional state using union types like T | null and safely update state without TypeScript errors.
The Problem: Nullable Complex State
Sometimes your state starts as null (data not loaded yet) and becomes a complex object later. TypeScript needs to know both possibilities exist:
const [user, setUser] = useState<User | null>(null);
Without the union type, TypeScript assumes your state is always User, and passing null triggers errors.
Accessing Properties Safely
When state might be null, you can't directly access properties:
interface User {
name: string;
email: string;
}
const [user, setUser] = useState<User | null>(null);
// ❌ Error: Object is possibly 'null'
console.log(user.name);
// ✅ Safe: Check first
if (user) {
console.log(user.name);
}
// ✅ Safe: Optional chaining
console.log(user?.name);
Updating from Null to Value
TypeScript validates your updates match the union type:
// ✅ Valid: null to User
setUser({ name: "Alice", email: "alice@example.com" });
// ✅ Valid: User back to null
setUser(null);
// ❌ Error: Partial object missing required properties
setUser({ name: "Bob" });
Think of It As
A box labeled "might contain User OR might be empty." TypeScript forces you to check before assuming what's inside, preventing runtime crashes when accessing properties on null.
The union type T | null documents your intent: "this data isn't always available." Your code becomes self-documenting and safer.
Key Takeaway: Use useState<T | null>(null) for optional state, always check nullability before accessing properties, and TypeScript will catch accidental null-access errors at compile time.