How do you properly type the useState hook in a React component using TypeScript?
Short answer
TypeScript usually figures out the correct type automatically based on the initial value you give useState, but you can also specify the type explicitly inside angle brackets, which is especially useful when the initial value is null but the state will later hold a specific…
Advertisement
AModel answer
TypeScript usually figures out the correct type automatically based on the initial value you give useState, but you can also specify the type explicitly inside angle brackets, which is especially useful when the initial value is null but the state will later hold a specific object type.
// TypeScript infers this is a number automatically
const [count, setCount] = useState(0);
// Explicitly typed, useful when starting with null
type User = { name: string; age: number };
const [user, setUser] = useState<User | null>(null);Real-world example
A profile component correctly types its user state as either a User object or null, letting TypeScript warn the developer immediately if they try to access user.name without first checking that user is not null.
Likely follow-ups
- Why is it necessary to explicitly type useState when the initial value is null?
- How does TypeScript help prevent a common bug where you forget to check if a value is null before using it?
Related topics