TypeScript with React
Overview
React and TypeScript are the most common pairing in front-end development. Types make components self-documenting: the editor knows every prop, every usage is checked, and refactoring a component’s API shows you every place that needs to change. This lesson covers the patterns you’ll use in every React + TypeScript codebase. (If you’re new to React itself, our React course covers the concepts.)
Setting up
The quickest start is Vite’s React + TypeScript template:
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run devIt configures jsx: "react-jsx", moduleResolution: "bundler" and noEmit, installs @types/react and @types/react-dom, and runs tsc -b as part of npm run build. Component files use the .tsx extension — TypeScript with JSX.
As usual, Vite only strips types; type errors show in the editor and in the tsc step of the build.
Typing props
A component is a function whose single parameter is its props object, so props are just an object type:
type ButtonProps = {
label: string;
variant?: "primary" | "ghost";
onClick: () => void;
};
function Button({ label, variant = "primary", onClick }: ButtonProps) {
return <button className={variant} onClick={onClick}>{label}</button>;
}
<Button label="Save" onClick={save} />; // ✓
<Button onClick={save} />;
// error TS2741: Property 'label' is missing in type '{ onClick: () => void; }' but required in type 'ButtonProps'.Destructuring with defaults keeps optional props easy to use. Literal unions ("primary" | "ghost") replace the “magic string” props that cause so many UI bugs. A discriminated union of props can even model components whose props depend on each other — { kind: "link"; href: string } | { kind: "button"; onClick: () => void }.
children
Anything React can render — elements, strings, numbers, arrays, null — is a React.ReactNode:
import type { ReactNode } from "react";
function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}Events
Inline handlers are typed from context — no annotation needed:
<input onChange={(e) => setName(e.target.value)} /> // e: ChangeEvent<HTMLInputElement>When you write the handler as a separate function, use React’s event types:
import type { ChangeEvent, FormEvent } from "react";
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setName(event.target.value);
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
}Tip: write the handler inline first, hover over the parameter to see its type, then extract it.
Hooks
useState
useState infers from the initial value:
const [count, setCount] = useState(0); // number
const [name, setName] = useState(""); // string
setCount("3"); // ✗ errorWhen the initial value doesn’t show the full type — typically null or an empty array — pass a type argument:
const [user, setUser] = useState<User | null>(null);
const [tags, setTags] = useState<string[]>([]);Then TypeScript makes you handle null before using user — the null and undefined lesson in action.
useRef
const inputRef = useRef<HTMLInputElement>(null);
// …
inputRef.current?.focus(); // current: HTMLInputElement | null
<input ref={inputRef} />;useReducer with discriminated unions
For state with several kinds of updates, useReducer plus a discriminated union of actions is a perfect match:
type Action =
| { type: "add"; title: string }
| { type: "toggle"; id: string }
| { type: "clear-done" };
function tasksReducer(state: Task[], action: Action): Task[] {
switch (action.type) {
case "add": return [...state, { id: crypto.randomUUID(), title: action.title, done: false }];
case "toggle": return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case "clear-done": return state.filter((t) => !t.done);
}
}
const [tasks, dispatch] = useReducer(tasksReducer, []);
dispatch({ type: "toggle", id: "1" }); // ✓
dispatch({ type: "toggle" }); // ✗ id is missingEach action carries exactly the data it needs, and adding a new action type shows you every reducer that must handle it.
Custom hooks
Custom hooks are typed functions. Return an object (or a tuple, typed with as const) so callers get precise types:
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((v) => !v);
return [on, toggle] as const; // readonly [boolean, () => void]
}Generic components
Components can be generic, like functions. TypeScript infers the type parameter from the props:
type ListProps<T> = {
items: T[];
getKey: (item: T) => string;
render: (item: T) => ReactNode;
};
function List<T>({ items, getKey, render }: ListProps<T>) {
return <ul>{items.map((item) => <li key={getKey(item)}>{render(item)}</li>)}</ul>;
}
<List items={users} getKey={(u) => u.id} render={(u) => u.name} />; // u: UserWrapping native elements
To make a component that accepts every prop a native <button> does, plus your own, build on ComponentProps:
import type { ComponentProps } from "react";
type FancyButtonProps = ComponentProps<"button"> & { variant?: "primary" | "ghost" };
function FancyButton({ variant = "primary", className, ...rest }: FancyButtonProps) {
return <button className={`btn-${variant} ${className ?? ""}`} {...rest} />;
}
<FancyButton type="submit" disabled onClick={(e) => e.currentTarget.blur()}>Save</FancyButton>;All the standard attributes — type, disabled, aria-*, event handlers — are typed and autocompleted.
Data from the server
Data fetched in a component is external data: validate it (Validating external data) instead of casting res.json() to your type. Libraries such as TanStack Query and tRPC carry types from the request to the component when paired with a schema.
Remember: props are object types, events have specific types (hover to find them), give
useStatea type argument when it starts empty, and model reducer actions as a discriminated union.
A typed task list
In src/TaskApp.tsx, write: (1) a Badge component with props { tone: "neutral" | "success" | "warning"; children: React.ReactNode }; (2) a reducer tasksReducer(state: Task[], action: Action): Task[] where Action is a discriminated union of add (with title), toggle (with id) and clear-done, using an exhaustive switch; (3) a generic List<T> component with props items: T[], getKey: (item: T) => string and render: (item: T) => React.ReactNode; (4) a TaskApp component using useReducer, a controlled <input> with a typed onChange, and a form onSubmit that dispatches add. Render TaskApp to a string (with renderToStaticMarkup from react-dom/server) after seeding two tasks, and print it, plus the result of running the reducer through a few actions.
import { useReducer, useState } from "react";
import { renderToStaticMarkup } from "react-dom/server";
type Task = { id: string; title: string; done: boolean };
// 1. Badge
// 2. Action + tasksReducer
// 3. List<T>
// 4. TaskAppimport { useReducer, useState, type ChangeEvent, type FormEvent, type ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
type Task = { id: string; title: string; done: boolean };
// 1. Badge
type BadgeProps = { tone: "neutral" | "success" | "warning"; children: ReactNode };
function Badge({ tone, children }: BadgeProps) {
return <span className={`badge badge-${tone}`}>{children}</span>;
}
// 2. Action + tasksReducer
type Action =
| { type: "add"; title: string }
| { type: "toggle"; id: string }
| { type: "clear-done" };
function tasksReducer(state: Task[], action: Action): Task[] {
switch (action.type) {
case "add":
return [...state, { id: String(state.length + 1), title: action.title, done: false }];
case "toggle":
return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case "clear-done":
return state.filter((t) => !t.done);
default: {
const unreachable: never = action;
return unreachable;
}
}
}
// 3. List<T>
type ListProps<T> = {
items: T[];
getKey: (item: T) => string;
render: (item: T) => ReactNode;
};
function List<T>({ items, getKey, render }: ListProps<T>) {
return <ul>{items.map((item) => <li key={getKey(item)}>{render(item)}</li>)}</ul>;
}
// 4. TaskApp
function TaskApp({ initial }: { initial: Task[] }) {
const [tasks, dispatch] = useReducer(tasksReducer, initial);
const [title, setTitle] = useState("");
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setTitle(event.target.value);
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (title.trim()) dispatch({ type: "add", title: title.trim() });
setTitle("");
}
return (
<section>
<form onSubmit={handleSubmit}>
<input value={title} onChange={handleChange} placeholder="New task" />
</form>
<List
items={tasks}
getKey={(t) => t.id}
render={(t) => (
<>
{t.title} <Badge tone={t.done ? "success" : "warning"}>{t.done ? "done" : "to do"}</Badge>
</>
)}
/>
</section>
);
}
const seeded = tasksReducer(tasksReducer([], { type: "add", title: "Write lesson" }), { type: "add", title: "Review" });
console.log(renderToStaticMarkup(<TaskApp initial={tasksReducer(seeded, { type: "toggle", id: "1" })} />));
const after = [
{ type: "toggle", id: "2" },
{ type: "clear-done" },
] satisfies Action[];
console.log(after.reduce(tasksReducer, seeded).map((t) => t.title)); // [ 'Write lesson' ]Summary
- Props are an object type: required, optional (
?) and union-typed props are all checked at every usage. - Type
childrenasReact.ReactNode; event handlers get types likeChangeEvent<HTMLInputElement>. useStateinfers from its initial value; pass a type argument when it starts empty (useState<User | null>(null)).useReducerwith a discriminated-unionActiontype gives exhaustive, type-safe state updates.- Generic components (
List<T>) andComponentProps<"button">keep reusable components precise.