Lesson 25 of 37Real projects
React with TypeScript
Type props, children, refs, events, hooks, reducers, context, actions and either-or props so the compiler catches React bugs for you.
Almost every professional React codebase in 2026 is written in TypeScript. Types turn "undefined is not a function" at runtime into a red squiggle in your editor, and they document your components: hover a prop and you see exactly what it accepts. You already know TypeScript basics from the JavaScript & TypeScript course; this lesson is the React-specific part.
A note on the previews: TypeScript in the runnable blocks is stripped, not checked, so they run even with type mistakes. Your editor and tsc are where the checking happens, and the quizzes here show the errors you would see.
Typing props
Describe a component's props with a type or an interface, then annotate the destructured parameter. Optional props get ?; give them a default in the destructuring.
type BadgeProps = {
label: string;
tone?: "neutral" | "success" | "danger"; // a union of allowed strings
count?: number;
};
function Badge({ label, tone = "neutral", count }: BadgeProps) {
return <span className={`badge badge-${tone}`}>{label}{count !== undefined && ` (${count})`}</span>;
}
<Badge label="Builds" tone="success" count={3} />; // OK
<Badge label="Builds" tone="green" />; // Error: "green" is not assignableComponents that wrap other content take children. Type it as React.ReactNode, which accepts anything React can render: elements, strings, numbers, arrays, null, undefined, and booleans.
children be text, an element, a list of elements, or nothing?Typing children and render props
React.ReactNode is the right default for children, but it is not the only shape children can take, and a few related types come up in code review.
React.PropsWithChildren<P> adds an optional children?: ReactNode to your own props type. It saves a line, but it makes children optional, which is wrong for a Card that is meaningless without content. Write children: React.ReactNode yourself when children are required.
React.ReactElement is narrower than ReactNode: exactly one element, no strings, no arrays, no null. Use it only when you really need an element, for example a prop you will pass to cloneElement. You cannot use types to say "children must be <Tab> elements". Every JSX expression has the same type to the compiler, so <Tabs><div /></Tabs> type-checks even if you wrote children: ReactElement<TabProps>. Enforce structure with a typed data prop (tabs: { id: string; label: string }[]) or check at runtime.
Children can also be a function. This is the render prop pattern: the component owns some state or behaviour and lets the caller decide how to render it. The type says exactly what the caller receives.
Inside the arrow, isOpen and toggle are typed with no annotations, because TypeScript infers them from the children type. Render props were everywhere before hooks. Today a custom hook (useDisclosure()) is usually simpler, but you still meet render props in table, virtual list and form libraries where the library controls when each row renders.
On React.FC: typing a component as const Card: React.FC<CardProps> = ... is allowed, and since React 18's types it no longer adds a hidden children prop. Most teams still prefer plain functions with typed parameters, because they work with generics and read the same as every other function.
Typing events
Inline handlers are typed for you: in onChange={(e) => ...}, TypeScript already knows e. When you pull a handler out into a named function, annotate the event with React's event types. The generic parameter is the element the handler is attached to.
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setName(e.target.value); // e.target is an HTMLInputElement, so .value is a string
}
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
}
function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
console.log(e.clientX, e.currentTarget.disabled);
}
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter") save();
}A shortcut when you only care about the handler type as a whole: const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => ....
Match the handler to its event type.
Typing state
useState infers its type from the initial value: useState(0) is a number, useState("") a string. Pass a generic when the initial value does not show the full type, typically null or an empty array.
const [count, setCount] = useState(0); // number, inferred
const [user, setUser] = useState<User | null>(null); // starts empty, filled later
const [tags, setTags] = useState<string[]>([]); // [] alone would be never[]
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle");setItems([...items, "milk"]) here?const [items, setItems] = useState([]);
Typing custom hooks: tuples and as const
When a custom hook returns two values in an array, like useState does, TypeScript does not infer what you expect.
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((o) => !o);
return [on, toggle];
// inferred return type: (boolean | (() => void))[]
}
const [isOpen, toggleOpen] = useToggle();
toggleOpen(); // Error: not all constituents of type 'boolean | (() => void)' are callable.An array literal is inferred as an array of "any of these", so each element could be a boolean or a function. Tell TypeScript it is a fixed-length tuple, either with as const or with an explicit return type:
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((o) => !o);
return [on, toggle] as const; // readonly [boolean, () => void]
}
function useToggleExplicit(initial = false): [boolean, () => void] {
const [on, setOn] = useState(initial);
return [on, () => setOn((o) => !o)];
}Some guidelines for hook types that hold up in a shared codebase:
- Return a tuple for two values the caller will want to rename (
const [isMenuOpen, toggleMenu] = useToggle()). Return an object for three or more, so callers pick by name and you can add fields later without breaking anyone. - Write an explicit return type on hooks other people import. Inferred types can change silently when you edit the body, and an explicit type turns that into an error at the source.
- Make hooks generic when the caller decides the type:
function useLocalStorage<T>(key: string, initial: T): [T, (value: T) => void]. TypeScript infersTfrominitial, souseLocalStorage("theme", "dark")givesstring.
return [user, isLoading]; where user is User | null and isLoading is boolean, with no as const or return type. What type does the caller get for the first element?Reducers with discriminated unions
Reducers are where TypeScript pays off most. Model actions as a discriminated union: every member has a type field with a different literal string. Inside switch (action.type), TypeScript narrows the action, so each branch only sees the fields that action has.
Now dispatch({ type: "setStep" }) without step, or dispatch({ type: "incremnet" }) with a typo, are compile errors. Because the function declares it returns State and every case returns, TypeScript also checks the switch is exhaustive: add a new action to the union and forget its case, and you get an error.
case "increment": in the reducer above, what happens if you write action.step?Typing context
Context needs a type for its value, and a decision about the default. A common, safe pattern: default to null, and wrap useContext in a custom hook that throws a helpful error if a component is used outside the provider. Consumers then get a non-null type.
import { createContext, useContext, useState } from "react";
type Theme = "light" | "dark";
type ThemeContextValue = { theme: Theme; toggle: () => void };
const ThemeContext = createContext<ThemeContextValue | null>(null);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
const toggle = () => setTheme((t) => (t === "light" ? "dark" : "light"));
return <ThemeContext value={{ theme, toggle }}>{children}</ThemeContext>;
}
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used inside <ThemeProvider>");
return ctx;
}(In React 19 you can render <ThemeContext value={...}> directly; <ThemeContext.Provider> still works.)
The provider is the only place that creates the value, and createContext<ThemeContextValue | null> fixes its type.
Generic components
Some components work with any item type: lists, tables, selects. Make the component generic, and TypeScript infers T from the props at each use, so renderItem knows the exact item shape.
In the first Select, T is Plan, so p.name autocompletes. In the second, T is number. One component, fully typed for both. (In a .tsx file, an arrow-function generic needs a trailing comma, <T,>(props) => ..., so the parser does not read <T> as JSX. Function declarations avoid that.)
Wrapping native elements with ComponentProps
When you build your own Button or Input, you want it to accept everything the native element does (type, disabled, aria-*, onClick) without listing them by hand. React.ComponentProps<"button"> is the full prop type of a <button>; extend it with your own props and spread the rest.
type ButtonProps = React.ComponentProps<"button"> & {
variant?: "primary" | "ghost";
};
export function Button({ variant = "primary", className = "", ...rest }: ButtonProps) {
return <button className={`btn btn-${variant} ${className}`} {...rest} />;
}
<Button type="submit" disabled={isSaving} aria-label="Save draft" variant="ghost" />; // all typedBecause ComponentProps<"button"> includes ref in React 19, the spread forwards a ref too. Use ComponentProps<typeof Card> to grab the props of one of your own components.
ref as a prop in React 19
Before React 19, a function component could not receive ref like other props. To let a parent focus your custom input you wrapped it in forwardRef, and its generic order (forwardRef<HTMLInputElement, Props>) confused everyone. In React 19, ref is an ordinary prop for function components. Type it with React.Ref<T>, where T is the DOM element it will point at.
The same component before React 19, which you will still see in most existing code:
const SearchInput = forwardRef<HTMLInputElement, { label: string }>(function SearchInput({ label }, ref) {
return <label>{label} <input ref={ref} type="search" /></label>;
});forwardRef still works in React 19, but the React team has said it will be deprecated, and there is an official codemod to remove it (see the React 19 upgrade guide). For new code, take ref as a prop. If your props extend React.ComponentProps<"input">, the ref type is already included.
Three type changes from React 19 catch people during upgrades:
useRefnow requires an argument.useRef<HTMLDivElement>(null)returnsRefObject<HTMLDivElement | null>, and itscurrentis always writable. The old split betweenRefObjectandMutableRefObjectis gone.- Ref callbacks may return a cleanup function, so TypeScript now rejects a callback that returns anything else.
ref={(el) => (nodeRef = el)}is an error because the assignment returnsel. Use a block body:ref={(el) => { nodeRef = el; }}. - Element refs start as
nulland are filled after the commit, soinputRef.currentisT | nulleverywhere. That?.ininputRef.current?.focus()is not noise.
Discriminated-union props
Some components take one set of props or another, never both. A Button that is either a link (href) or an action (onClick). An Alert that is either dismissible (and then needs onDismiss) or not. Optional props for everything allow nonsense like <Button href="/x" onClick={save} />. A union of prop shapes makes nonsense a compile error.
as is the discriminant, like type in a reducer action. Checking props.as narrows props to one member, so props.href only exists in the link branch.
When there is no natural discriminant, mark the other side's props as never. A property of type never can only be left out, so passing both becomes an error:
type Controlled = { value: string; onChange: (v: string) => void; defaultValue?: never };
type Uncontrolled = { defaultValue?: string; value?: never; onChange?: never };
type TextFieldProps = { label: string } & (Controlled | Uncontrolled);
<TextField label="Name" value={name} onChange={setName} />; // OK
<TextField label="Name" defaultValue="Ada" />; // OK
<TextField label="Name" value={name} defaultValue="Ada" />; // ErrorOne trap: you cannot destructure a union's props in the parameter list the way you are used to. function Button({ as, href }: ButtonProps) is an error, because href does not exist on every member. And with function Button({ as, ...rest }: ButtonProps), checking as === "link" does not narrow rest, so rest.href is still an error. Keep props whole until you have narrowed, then destructure inside the branch.
ButtonProps union above, which call is a compile error?Typing useActionState and form actions
The actions lesson covers how useActionState behaves. Here is how to type it so the compiler checks your form logic too. The action receives the previous state and the submitted FormData, and returns the next state. If you type the action, useActionState infers everything else.
import { useActionState } from "react";
type Fields = { email: string; name: string };
type SignupState =
| { status: "idle" }
| { status: "invalid"; errors: Partial<Record<keyof Fields, string>>; values: Fields }
| { status: "done"; email: string };
function readText(data: FormData, key: keyof Fields): string {
const v = data.get(key); // FormDataEntryValue | null, which is string | File | null
return typeof v === "string" ? v.trim() : "";
}
async function signup(prev: SignupState, data: FormData): Promise<SignupState> {
const values = { email: readText(data, "email"), name: readText(data, "name") };
const errors: Partial<Record<keyof Fields, string>> = {};
if (!values.email.includes("@")) errors.email = "Enter a valid email";
if (!values.name) errors.name = "Enter your name";
if (Object.keys(errors).length) return { status: "invalid", errors, values };
await saveUser(values); // your API call
return { status: "done", email: values.email };
}
export function SignupForm() {
const [state, formAction, isPending] = useActionState(signup, { status: "idle" });
// state: SignupState, formAction: (payload: FormData) => void, isPending: boolean
if (state.status === "done") return <p>Check {state.email} for a link.</p>;
const errors = state.status === "invalid" ? state.errors : {};
return (
<form action={formAction}>
<input name="email" defaultValue={state.status === "invalid" ? state.values.email : ""} />
{errors.email && <p>{errors.email}</p>}
{/* ...name field, submit button using isPending */}
</form>
);
}The details that matter:
formData.get()returnsstring | File | null, never your field's type. Never cast it withas string; a missing field becomesnulland a file input gives aFile. A smallreadTexthelper, or a schema library like Zod withsafeParse, turns it into real types at the boundary.keyof Fieldsties field names to one type, so a typo indata.get("emial")orerrors.emialis a compile error.- The state is a discriminated union, like the remote-data union in the conditional rendering lesson, so
state.errorsonly exists when the status isinvalid. - A plain
<form action>accepts a function typed(formData: FormData) => void | Promise<void>. WithuseActionState, pass the returnedformAction, not your original function. - If the action is a Next.js Server Action, it runs on the server, and its argument types are a promise you cannot enforce: anyone can call it with anything. Validate inside the action, always.
const email = formData.get("email") as string a bad idea in an action?A generic List<T> component
Write a generic component List<T> that renders any array:
type ListProps<T> = {
items: T[];
getKey: (item: T) => string;
renderItem: (item: T) => React.ReactNode;
emptyText: string;
};- With items: a
<ul>with one<li>per item, containingrenderItem(item). - With no items: a
<p>withemptyText(no<ul>).
App already uses it for users (Ada (admin), Sam (editor), Priya (viewer)) and tags (react, typescript). The Clear users button empties the users list, which should then show No users yet.
A typed cart reducer
Write cartReducer(state, action) for a shopping cart. The action is a discriminated union on type:
type CartState = { items: { id: string; qty: number }[] };
type CartAction =
| { type: "add"; id: string }
| { type: "remove"; id: string }
| { type: "setQty"; id: string; qty: number }
| { type: "clear" };add: increaseqtyby 1, or append{ id, qty: 1 }if the item is new.remove: drop the item (no change if it is not there).setQty: set the quantity; aqtyof0or less removes the item.clear: empty the cart.
Never mutate state; return a new object.
- React.ReactNode
- Anything React can render: elements, strings, numbers, arrays, null, undefined, booleans. The type for
children. - React.ChangeEvent<T>
- The event type for
onChange, whereTis the element, such asHTMLInputElement. - discriminated union
- A union of object types sharing a literal
typefield, whichswitchuses to narrow to one member. - generic component
- A component with a type parameter, like
List<T>, whose prop types are inferred from usage. - ComponentProps
React.ComponentProps<"button">gives all props of a native element (or of a component viatypeof).- React.Ref<T>
- The type of a
refprop: a ref object or a ref callback for an element of typeT, or null. - render prop
- A prop, often
children, that is a function returning JSX, so the caller controls rendering. - as const tuple
- Marking an array literal
as constso TypeScript infers a fixed-length readonly tuple, not a union array. - FormDataEntryValue
- What
FormData.getreturns:string | File, ornullwhen the field is missing.