Sub topic 7
Typing useState
This chapter explains how TypeScript infers the type of useState, when you need to supply the type yourself, and how to model state that changes shape over time. It assumes you know basic React (function components, props, state, JSX) and TypeScript fundamentals (interfaces, unions, generics). It also assumes your project already has strict turned on, as set up earlier in this tutorial. Without strict, several of the errors shown below would not appear.
How useState is typed
useState is a generic function. Its simplified signature is:
function useState<S>(
initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>];S is the type of the state value. The hook returns a tuple: the current value, and a setter. The setter has the type Dispatch<SetStateAction<S>>, which means it accepts either a new value of type S or a function that takes the previous value and returns a new one.
You can leave S out, and TypeScript infers it from the initial value. You can also write it yourself as useState<S>(...). Most of the skill in typing useState is knowing which of the two the situation needs.
Let inference work for primitives
When the initial value fully describes the state, inference is enough.
import { useState, type ChangeEvent } from "react";
export function NameField() {
const [name, setName] = useState(""); // string
const [count, setCount] = useState(0); // number
const [visible, setVisible] = useState(true); // boolean
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setName(e.target.value);
setCount(e.target.value.length);
}
return (
<div>
<input value={name} onChange={handleChange} />
<button onClick={() => setVisible((v) => !v)}>Toggle</button>
{visible && <p>{count} characters</p>}
</div>
);
}Inference widens literals. useState("") gives string, not the literal type "". Likewise useState(0) gives number. This is what you want here, because the state must accept other strings and numbers later.
The setter is checked against the inferred type. setName(42) is a compile error: Argument of type 'number' is not assignable to parameter of type 'SetStateAction<string>'. The functional form setVisible((v) => !v) also type-checks, and v is inferred as boolean. You never need to annotate it.
When to supply the type argument
Inference only sees the initial value. Supply the type argument when the initial value is narrower than the values the state will hold later. There are four common cases.
State that starts empty
If the state is "nothing yet", the initial value is null or undefined. Inference would produce null as the whole type, and you could never set a real value. Use a union.
import { useState } from "react";
interface User {
id: number;
name: string;
}
export function Profile() {
const [user, setUser] = useState<User | null>(null);
return (
<div>
<button onClick={() => setUser({ id: 1, name: "Ada" })}>Load</button>
<p>{user ? user.name : "No user"}</p>
</div>
);
}Because the type is User | null, reading user.name without a check is a compile error. TypeScript narrows the type inside the user ? ... : ... branch, so the compiler forces you to handle the empty case.
Empty arrays
In strict mode, useState([]) infers never[]. Nothing can be added to a never[], so the setter rejects real items. Always provide the element type.
import { useState } from "react";
export function TagList() {
const [tags, setTags] = useState<string[]>([]);
return (
<div>
<button onClick={() => setTags((prev) => [...prev, `tag-${prev.length + 1}`])}>
Add tag
</button>
<ul>
{tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul>
</div>
);
}String literal unions
If a value can be only a few specific strings, say so. Otherwise it widens to string and typos go unnoticed.
import { useState } from "react";
type Tab = "overview" | "settings" | "billing";
export function Tabs() {
const [tab, setTab] = useState<Tab>("overview");
return (
<nav>
{(["overview", "settings", "billing"] as const).map((t) => (
<button key={t} onClick={() => setTab(t)} disabled={t === tab}>
{t}
</button>
))}
</nav>
);
}With useState<Tab>, calling setTab("setings") fails at compile time. Without the argument, useState("overview") would be string and the typo would compile.
Objects with optional fields
If the initial object omits a field that appears later, inference locks in the smaller shape. Declare the full type, and mark the late fields optional.
interface Filters {
query: string;
minPrice?: number;
}Then call useState<Filters>({ query: "" }).
Deciding whether to annotate
The diagram summarizes the decision.
Lazy initializers and functional updates
useState accepts a function as the initial value. React calls it once, on the first render. TypeScript infers S from the function's return type.
import { useState } from "react";
interface Settings {
theme: "light" | "dark";
fontSize: number;
}
function readSettings(): Settings {
const raw = localStorage.getItem("settings");
return raw ? (JSON.parse(raw) as Settings) : { theme: "light", fontSize: 14 };
}
export function SettingsPanel() {
const [settings, setSettings] = useState(readSettings);
return (
<button
onClick={() =>
setSettings((prev) => ({ ...prev, fontSize: prev.fontSize + 1 }))
}
>
Font size: {settings.fontSize}
</button>
);
}Passing readSettings itself, not readSettings(), is what makes it lazy. The type is inferred as Settings. In the updater, prev is also Settings, so a typo like prev.fontsize is caught.
JSON.parse returns any, so the as Settings cast is unchecked. If the stored data might be stale or malformed, validate it with a runtime schema library instead of trusting the cast.
Passing state setters to children
The setter's type is Dispatch<SetStateAction<T>>. If a child only needs to report a new value, give it a narrower callback type instead.
import { useState, type Dispatch, type SetStateAction } from "react";
interface StepperProps {
setCount: Dispatch<SetStateAction<number>>;
}
function Stepper({ setCount }: StepperProps) {
return <button onClick={() => setCount((c) => c + 1)}>+1</button>;
}
interface ResetProps {
onReset: (value: number) => void;
}
function Reset({ onReset }: ResetProps) {
return <button onClick={() => onReset(0)}>Reset</button>;
}
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<Stepper setCount={setCount} />
<Reset onReset={setCount} />
</div>
);
}Reset is easier to reuse and test because it does not depend on React's types. A setter is assignable to (value: number) => void, so onReset={setCount} compiles. Use the Dispatch<SetStateAction<T>> form only when the child needs the functional update.
Modeling changing shape with a union
Several separate useState calls for loading, error, and data can drift into impossible combinations, such as "loading with an error". A discriminated union makes those combinations unrepresentable.
import { useState } from "react";
interface User {
id: number;
name: string;
}
type RemoteUser =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; message: string }
| { status: "success"; user: User };
async function fetchUser(): Promise<User> {
return { id: 1, name: "Ada" };
}
export function UserLoader() {
const [state, setState] = useState<RemoteUser>({ status: "idle" });
async function load() {
setState({ status: "loading" });
try {
setState({ status: "success", user: await fetchUser() });
} catch (err) {
setState({
status: "error",
message: err instanceof Error ? err.message : "Unknown error",
});
}
}
return (
<div>
<button onClick={load}>Load</button>
{state.status === "loading" && <p>Loading...</p>}
{state.status === "error" && <p>{state.message}</p>}
{state.status === "success" && <p>{state.user.name}</p>}
</div>
);
}Inside each state.status === ... check, TypeScript narrows state. state.message exists only for "error", and state.user only for "success". The catch variable is unknown under strict, so the instanceof Error check is needed before reading .message.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `Argument of type 'X' is not assignable to parameter of type 'never'` when updating an array | `useState([])` infers `never[]` | Write `useState<X[]>([])` | |
| `Argument of type '{...}' is not assignable to parameter of type 'SetStateAction<null>'` | `useState(null)` infers `null` | Write `useState<T \ | null>(null)` |
| `'user' is possibly 'null'` | The state type includes `null` and you read a field without a check | Narrow with `if`, a ternary, or `?.` | |
| Literal typos compile | The state widened to `string` | Add a literal union as the type argument | |
| A function stored as state runs immediately | React treats a function argument as a lazy initializer | Wrap it: `useState<() => void>(() => myFn)` |
The last row is a runtime trap that the types do not catch. When the value you want to store is itself a function, return it from an initializer. The same applies to the setter, where you write setFn(() => myFn).
Exercises
Exercise
A component declares const [items, setItems] = useState([]); and then calls setItems(["a", "b"]). Under strict, this fails to compile. Why does it fail, and what is the one-line fix?
Show answer
With an empty array literal, TypeScript infers never[], so the setter only accepts never[] and rejects string[]. Supply the element type: const [items, setItems] = useState<string[]>([]);.
Exercise
You have const [selected, setSelected] = useState<Product | null>(null); and render <p>{selected.name}</p>. What error do you get, and how would you fix the JSX without changing the state type?
Show answer
TypeScript reports that selected is possibly null. Narrow it before reading, for example <p>{selected ? selected.name : "Nothing selected"}</p> or <p>{selected?.name}</p>.