Skip to content

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.

19 min read0/7 questions

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 assignable

Components 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.

ReactTypedProps.tsx
type CardProps = { title: string; footer?: React.ReactNode; children: React.ReactNode;}; function Card({ title, footer, children }: CardProps) { return ( <section style={{ border: "1px solid #ccc", borderRadius: 8, padding: 12, maxWidth: 320 }}> <h3 style={{ marginTop: 0 }}>{title}</h3> {children} {footer && <footer style={{ marginTop: 8, opacity: 0.7 }}>{footer}</footer>} </section> );} export default function App() { return ( <Card title="Deploy" footer={<small>Last run 2 minutes ago</small>}> <p>All 42 checks passed.</p> </Card> );}
Quick check
Which type lets children be text, an element, a list of elements, or nothing?
Need a nudge? A hint rules out a wrong answer.

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.

ReactRenderProp.tsx
import { useState } from "react"; type DisclosureApi = { isOpen: boolean; toggle: () => void }; function Disclosure({ children }: { children: (api: DisclosureApi) => React.ReactNode }) { const [isOpen, setIsOpen] = useState(false); return <>{children({ isOpen, toggle: () => setIsOpen((o) => !o) })}</>;} export default function App() { return ( <Disclosure> {({ isOpen, toggle }) => ( <div> <button aria-expanded={isOpen} onClick={toggle}> {isOpen ? "Hide" : "Show"} shipping details </button> {isOpen && <p>Orders ship within 2 business days.</p>} </div> )} </Disclosure> );}

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 pairs0/5 matched

Match the handler to its event type.

Choose an item, then its match on the other side.

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");
Quick check
What does TypeScript say about setItems([...items, "milk"]) here?
const [items, setItems] = useState([]);
Need a nudge? A hint rules out a wrong answer.

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 infers T from initial, so useLocalStorage("theme", "dark") gives string.
Quick check
A hook ends with 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?
Need a nudge? A hint rules out a wrong answer.

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.

ReactTypedReducer.tsx
import { useReducer } from "react"; type State = { count: number; step: number };type Action = | { type: "increment" } | { type: "decrement" } | { type: "setStep"; step: number } | { type: "reset" }; function reducer(state: State, action: Action): State { switch (action.type) { case "increment": return { ...state, count: state.count + state.step }; case "decrement": return { ...state, count: state.count - state.step }; case "setStep": return { ...state, step: action.step }; // action.step only exists here case "reset": return { count: 0, step: 1 }; }} export default function App() { const [state, dispatch] = useReducer(reducer, { count: 0, step: 1 }); return ( <div style={{ display: "flex", gap: 8, alignItems: "center" }}> <button onClick={() => dispatch({ type: "decrement" })}>−</button> <strong>{state.count}</strong> <button onClick={() => dispatch({ type: "increment" })}>+</button> <label> Step{" "} <select value={state.step} onChange={(e) => dispatch({ type: "setStep", step: Number(e.target.value) })}> {[1, 5, 10].map((n) => <option key={n} value={n}>{n}</option>)} </select> </label> <button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> );}

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.

Quick check
Inside case "increment": in the reducer above, what happens if you write action.step?
Need a nudge? A hint rules out a wrong answer.

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.

features/theme/ThemeContext.tsx
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.)

Where the context type flows
ThemeProvidervalue: ThemeContextValueThemeToggleuseTheme() → ThemeContextValueHeaderArticleuseTheme() → ThemeContextValueMainLayoutSettingsoutside the providerroot

The provider is the only place that creates the value, and createContext<ThemeContextValue | null> fixes its type.

1/3

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.

ReactGenericSelect.tsx
import { useState } from "react"; type SelectProps<T> = { options: T[]; value: T; getLabel: (option: T) => string; onChange: (option: T) => void;}; function Select<T>({ options, value, getLabel, onChange }: SelectProps<T>) { return ( <div style={{ display: "flex", gap: 6 }}> {options.map((option) => ( <button key={getLabel(option)} aria-pressed={option === value} style={{ fontWeight: option === value ? 700 : 400 }} onClick={() => onChange(option)} > {getLabel(option)} </button> ))} </div> );} type Plan = { id: string; name: string; price: number };const PLANS: Plan[] = [ { id: "free", name: "Free", price: 0 }, { id: "pro", name: "Pro", price: 12 },]; export default function App() { const [plan, setPlan] = useState(PLANS[0]); const [size, setSize] = useState(2); return ( <div style={{ display: "grid", gap: 8 }}> <Select options={PLANS} value={plan} getLabel={(p) => p.name} onChange={setPlan} /> <Select options={[1, 2, 3]} value={size} getLabel={(n) => n + " seats"} onChange={setSize} /> <p>{plan.name} for {size} seats: ${plan.price * size}/month</p> </div> );}

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.

components/ui/Button.tsx
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 typed

Because 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.

ReactRefProp.tsx
import { useRef } from "react"; type SearchInputProps = { label: string; ref?: React.Ref<HTMLInputElement> }; function SearchInput({ label, ref }: SearchInputProps) { return ( <label> {label} <input ref={ref} type="search" /> </label> );} export default function App() { const inputRef = useRef<HTMLInputElement>(null); // RefObject<HTMLInputElement | null> return ( <div style={{ display: "flex", gap: 8, alignItems: "center" }}> <SearchInput label="Search" ref={inputRef} /> <button onClick={() => inputRef.current?.focus()}>Focus search</button> </div> );}

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:

  • useRef now requires an argument. useRef<HTMLDivElement>(null) returns RefObject<HTMLDivElement | null>, and its current is always writable. The old split between RefObject and MutableRefObject is 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 returns el. Use a block body: ref={(el) => { nodeRef = el; }}.
  • Element refs start as null and are filled after the commit, so inputRef.current is T | null everywhere. That ?. in inputRef.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.

ReactEitherOrProps.tsx
type LinkButtonProps = { as: "link"; href: string; children: React.ReactNode };type ActionButtonProps = { as: "button"; onClick: () => void; disabled?: boolean; children: React.ReactNode };type ButtonProps = LinkButtonProps | ActionButtonProps; function Button(props: ButtonProps) { const style = { padding: "6px 12px", border: "1px solid #888", textDecoration: "none", color: "inherit" }; if (props.as === "link") { return <a href={props.href} style={style}>{props.children}</a>; // props is LinkButtonProps here } return <button onClick={props.onClick} disabled={props.disabled} style={style}>{props.children}</button>;} export default function App() { return ( <div style={{ display: "flex", gap: 8 }}> <Button as="link" href="#docs">Read the docs</Button> <Button as="button" onClick={() => alert("Saved")}>Save</Button> </div> );}

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" />; // Error

One 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.

Quick check
With the ButtonProps union above, which call is a compile error?
Need a nudge? A hint rules out a wrong answer.

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.

features/signup/SignupForm.tsx
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() returns string | File | null, never your field's type. Never cast it with as string; a missing field becomes null and a file input gives a File. A small readText helper, or a schema library like Zod with safeParse, turns it into real types at the boundary.
  • keyof Fields ties field names to one type, so a typo in data.get("emial") or errors.emial is a compile error.
  • The state is a discriminated union, like the remote-data union in the conditional rendering lesson, so state.errors only exists when the status is invalid.
  • A plain <form action> accepts a function typed (formData: FormData) => void | Promise<void>. With useActionState, pass the returned formAction, 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.
Quick check
Why is const email = formData.get("email") as string a bad idea in an action?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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, containing renderItem(item).
  • With no items: a <p> with emptyText (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.

React
import { useState } from "react"; type User = { id: string; name: string; role: "admin" | "editor" | "viewer" }; type ListProps<T> = { items: T[]; getKey: (item: T) => string; renderItem: (item: T) => React.ReactNode; emptyText: string;}; function List<T>({ items, getKey, renderItem, emptyText }: ListProps<T>) { // Render a <ul> of <li>s, or a <p> with emptyText when there are no items. return null;} const START: User[] = [ { id: "u1", name: "Ada", role: "admin" }, { id: "u2", name: "Sam", role: "editor" }, { id: "u3", name: "Priya", role: "viewer" },]; export default function App() { const [users, setUsers] = useState<User[]>(START); return ( <div> <List items={users} getKey={(u) => u.id} renderItem={(u) => u.name + " (" + u.role + ")"} emptyText="No users yet" /> <List items={["react", "typescript"]} getKey={(tag) => tag} renderItem={(tag) => "#" + tag} emptyText="No tags" /> <button onClick={() => setUsers([])}>Clear users</button> </div> );}
ChallengeMedium

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: increase qty by 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; a qty of 0 or less removes the item.
  • clear: empty the cart.

Never mutate state; return a new object.

TypeScript
type CartItem = { id: string; qty: number };type CartState = { items: CartItem[] };type CartAction = | { type: "add"; id: string } | { type: "remove"; id: string } | { type: "setQty"; id: string; qty: number } | { type: "clear" }; function cartReducer(state: CartState, action: CartAction): CartState { // switch (action.type) { ... } return state;}
Key terms
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, where T is the element, such as HTMLInputElement.
discriminated union
A union of object types sharing a literal type field, which switch uses 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 via typeof).
React.Ref<T>
The type of a ref prop: a ref object or a ref callback for an element of type T, 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 const so TypeScript infers a fixed-length readonly tuple, not a union array.
FormDataEntryValue
What FormData.get returns: string | File, or null when the field is missing.