Sub topic 7
Typing useState
This chapter assumes you know basic React state and TypeScript generics and unions. It also assumes your project already uses the strict tsconfig.json from the setup chapter. Here you will learn when useState infers its type and when you must supply one.
How inference works
useState is a generic function. Its type parameter S is the type of the state value. When you pass an initial value, TypeScript infers S from it.
import { useState, type ChangeEvent } from "react";
export function NameField() {
const [name, setName] = useState("");
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setName(e.target.value);
}
return <input value={name} onChange={handleChange} />;
}The initial value "" makes name a string. setName accepts a string or an updater function (prev: string) => string. Calling setName(42) is a compile error. You do not need to write useState<string>("") here.
When inference is not enough
Inference only sees the initial value. It goes wrong in three common cases.
- The state starts empty, so the initial value says nothing about the later value.
- The initial value is an empty array or object.
- The state is a set of string literals, but inference widens it to
string.
State that starts as null
useState(null) infers the type null. Passing an object to the setter later would then fail. Use a union with null, and narrow it before you read it.
import { useRef, useState } from "react";
interface User {
id: number;
name: string;
}
export function Profile() {
const [user, setUser] = useState<User | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus</button>
<button onClick={() => setUser({ id: 1, name: "Ada" })}>Load</button>
<p>{user ? user.name : "No user"}</p>
</div>
);
}The expression user ? user.name : "No user" narrows user from User | null to User. Without the check, user.name is an error under strict.
Empty arrays
Under strict, useState([]) infers never[]. Nothing can be added to a never[], so setItems(["a"]) fails. Name the element type instead.
import { useState } from "react";
export function TagList() {
const [tags, setTags] = useState<string[]>([]);
return (
<div>
<button onClick={() => setTags((prev) => [...prev, `tag-${prev.length}`])}>
Add tag
</button>
<ul>
{tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul>
</div>
);
}The updater form (prev) => [...] gets prev typed as string[] automatically.
Literal unions
useState("idle") infers string, so any string would be accepted. A union keeps the state to the values you intend.
import { useState } from "react";
type Status = "idle" | "loading" | "error";
export function SaveButton() {
const [status, setStatus] = useState<Status>("idle");
return (
<button disabled={status === "loading"} onClick={() => setStatus("loading")}>
{status === "error" ? "Retry" : "Save"}
</button>
);
}Now setStatus("done") is a compile error, and comparing status === "eror" is flagged as well.
Common mistakes
- Writing
useState<User>(null). WithstrictNullChecksthis fails becausenullis not aUser. Add| nullto the type. - Using
as Useron an empty object, as inuseState({} as User). This hides missing fields, anduser.namebecomesundefinedat runtime while the compiler reports no error. - Storing several flags that cannot all be true together. A union such as
Statusis safer than three booleans.
Exercise
Exercise
A component keeps a selected product, which is absent until the user clicks one. The product has the shape { sku: string; price: number }. Write the useState line, and say why useState(null) does not work.
Show answer
const [selected, setSelected] = useState<Product | null>(null); with interface Product { sku: string; price: number }. useState(null) infers the state type as null, so calling setSelected with a product object is a type error. The explicit union tells TypeScript the state can be either value.