How to Type React Components and Hooks
Type props, children, events, state, refs and custom hooks in React 19 with TypeScript 6, with checked examples and the mistakes that cause most type errors.

Typing React well is mostly a short list of habits. Describe props with an interface, let the compiler infer what it can, annotate the places where inference has nothing to go on, and let the hook signatures do their job. This post walks through how to type React components and hooks in a project that uses React 19 with TypeScript 6.x. The same code works with the native TypeScript 7 compiler. It covers props and children, event handlers, useState, useRef, useReducer, context, and custom hooks, and it points out the spots where the types push back. The reference for the official recommendations is the React TypeScript guide, and the types themselves come from the @types/react package.
Typing props
A function component is a function that takes one argument, the props object. Type the argument and you have typed the component.
interface GreetingProps {
name: string;
excited?: boolean;
}
export function Greeting({ name, excited = false }: GreetingProps) {
return <p>{excited ? `Hello, ${name}!` : `Hello, ${name}`}</p>;
}There is no need for React.FC. It was popular because it added an implicit children prop in older type definitions, and that behavior was removed, so it now gives nothing that a plain parameter annotation does not. A plain function also reads better in editor tooltips, and it supports generics without extra syntax.
An optional prop gets a ? and a default in the destructuring pattern. Inside the function, excited is boolean, because the default removes undefined. Callers can omit it, and a call with the wrong type is an error.
import { Greeting } from "./greeting.tsx";
export const ok = <Greeting name="Ada" excited />;
export const bad = <Greeting name={42} />;use-greeting.tsx(4,35): error TS2322: Type 'number' is not assignable to type 'string'.Children
The type for anything React can render is ReactNode. Declare children explicitly in the props of a component that accepts it.
import type { ReactNode } from "react";
interface CardProps {
title: string;
children: ReactNode;
}
export function Card({ title, children }: CardProps) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}ReactNode covers elements, strings, numbers, fragments, arrays, null and undefined, which is what you want for a slot. Use ReactElement only when you need exactly one element, and use a render function type, such as (item: Item) => ReactNode, when the parent supplies data to the child. A frequent mistake is typing children as JSX.Element, which rejects strings and null and makes conditional rendering awkward.
Events
Handlers take React's synthetic event types, which are generic over the element.
import { useState } from "react";
import type { ChangeEvent, FormEvent } from "react";
export function EmailForm({ onSubmit }: { onSubmit: (email: string) => void }) {
const [email, setEmail] = useState("");
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setEmail(event.target.value);
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
onSubmit(email);
}
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={handleChange} />
<button type="submit">Send</button>
</form>
);
}ChangeEvent<HTMLInputElement> tells the compiler that event.target is an input, so value is a string. If you write the handler inline, as onChange={(e) => setEmail(e.target.value)}, you need no annotation at all, because the JSX attribute supplies the contextual type. Annotate a handler only when you declare it separately, as above.
State
useState infers its type from the initial value. That works for useState("") and useState(0). It fails where the initial value is less specific than the eventual one, such as null or an empty array.
import { useState } from "react";
interface User {
id: number;
name: string;
}
export function Profile() {
const [user, setUser] = useState<User | null>(null);
const [tags, setTags] = useState<string[]>([]);
return (
<div>
<button onClick={() => setUser({ id: 1, name: "Ada" })}>Load</button>
<button onClick={() => setTags((prev) => [...prev, "new"])}>Tag</button>
<p>{user ? user.name : "Nobody"}</p>
<p>{tags.length}</p>
</div>
);
}Without the type argument, useState(null) would infer null and setUser would reject a User. The functional update form, setTags((prev) => ...), gets prev typed as string[] from the declaration. Narrow user in the JSX with a conditional, the same way you would in any code.
Refs
For a DOM element, give useRef the element type and null as the initial value.
import { useRef } from "react";
export function FocusInput() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus</button>
</div>
);
}In React 19 types, useRef requires an argument, and useRef<HTMLInputElement>(null) produces a RefObject<HTMLInputElement | null>. The current value is null until the element mounts, so the optional chaining is required. For a mutable box that holds a value across renders, such as a timer id, pass a non-null initial value: useRef<number>(0).
useReducer with a discriminated union
A reducer is where a union of action types pays off.
import { useReducer } from "react";
type State = { count: number };
type Action = { type: "add"; amount: number } | { type: "reset" };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "add":
return { count: state.count + action.amount };
case "reset":
return { count: 0 };
}
}
export function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<button onClick={() => dispatch({ type: "add", amount: 2 })}>
{state.count}
</button>
);
}Inside the case "add" branch, the compiler knows action.amount exists. Dispatching { type: "add" } without amount is a compile error, and so is a type name that is not in the union. The reducer's return annotation catches a case that forgets to return.
Context
Context is the one place where an unavoidable undefined appears, because the provider may be missing. Model that directly, and hide it behind a hook.
import { createContext, useContext } from "react";
import type { ReactNode } from "react";
interface ThemeValue {
mode: "light" | "dark";
toggle: () => void;
}
const ThemeContext = createContext<ThemeValue | undefined>(undefined);
export function ThemeProvider({ children }: { children: ReactNode }) {
const value: ThemeValue = { mode: "light", toggle: () => {} };
return <ThemeContext value={value}>{children}</ThemeContext>;
}
export function useTheme(): ThemeValue {
const value = useContext(ThemeContext);
if (value === undefined) {
throw new Error("useTheme must be used inside ThemeProvider");
}
return value;
}The hook narrows undefined away once, so every consumer receives a plain ThemeValue. In React 19 the context object can be rendered directly as a provider, as shown. The thrown error is also a better failure than a confusing property access on undefined later.
Custom hooks
A custom hook is a function, so type its parameters and its return value. Return a tuple with as const when you want array destructuring with distinct types, and an object otherwise.
import { useCallback, useState } from "react";
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((v) => !v), []);
return [on, toggle] as const;
}as const makes the return type readonly [boolean, () => void] instead of (boolean | (() => void))[], so the caller can write const [open, toggleOpen] = useToggle() and get the right type for each name. For hooks with more than two or three values, return an object, which also makes the call site self describing.
Generic components
A component that works on a list of anything is a generic function. The type parameter goes on the function, and the props mention it.
import type { ReactNode } from "react";
interface SelectListProps<T> {
items: T[];
getKey: (item: T) => string;
render: (item: T) => ReactNode;
}
export function SelectList<T>({ items, getKey, render }: SelectListProps<T>) {
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{render(item)}</li>
))}
</ul>
);
}At the call site, the compiler infers T from items, so render receives the right type with no annotation. If you pass items={[{ id: 1, label: "A" }]}, then render={(x) => x.label} type checks, and x.missing does not. This is the reason to prefer a plain function over React.FC: a generic arrow function assigned to a typed constant cannot carry a type parameter cleanly, while a function declaration does it naturally.
Where inference helps and where it does not
Most of what makes React code feel heavy with types is over annotation. Do not annotate the return type of a component unless you have a reason. The compiler infers JSX.Element, and a hand written return type adds nothing but a place to be wrong. Do not annotate variables that are initialized with a typed expression, and do not annotate the parameters of inline callbacks passed to props, because the prop type supplies them.
Annotate where there is no source of information: a handler declared on its own line, a useState that starts empty, a useRef that starts null, a context default, and the props of every exported component. Those are the boundaries, and a boundary with an explicit type produces better error messages at the call site than an inferred one that changes by accident.
A related habit is to keep prop types close to the component and export them when other files need them. If a parent needs the child's props, derive them with ComponentProps<typeof Child> instead of importing a separate interface.
Common errors and what they mean
The error "Type 'string | undefined' is not assignable to type 'string'" in a prop usually means an optional value reached a required prop. Fix it at the source with a default or a guard, not with a non-null assertion.
The error "Argument of type 'X' is not assignable to parameter of type 'SetStateAction'" means the state type was inferred too narrowly from the first value, often a literal. Add a type argument to useState.
A hook called with the wrong number of dependencies is not a type error. Use the official React lint rules for that, since the compiler cannot see it.


