TypeScript in React: Typing Props, Hooks and Events
How props and state become verifiable contracts – and your editor reports errors before your users see them. From interface/type through useState generics and event types to useRef and utility types.
Someone renames a prop on a button component, the build passes, the page renders. Three days later, a ticket arrives from another team: empty button in the checkout dialog. Five call sites use this component, and none of them complained – JavaScript had no reason to. If you suggest TypeScript after a ticket like that, the first thing you hear is: “Isn’t that just more typing?”
Behind it lies a decision first, not a question of syntax. The decision is: Where do I want to pay for my integration errors? Without types, I pay late, in the browser, at the user’s end, often in a different team than the one that introduced the bug. With types, I pay early, in the editor, with a red squiggly line, before anything is built. The price can be named honestly: a few lines of type declarations and the discipline to keep them current. The effect is usually worth it, because an error the compiler catches never becomes a bug report, never a rollback, never a support request.
So TypeScript in React is neither an end in itself nor bureaucracy. A props signature becomes a promise that the compiler checks every time you save: “This component expects a label string and, optionally, a disabled flag.” Anyone who breaks it gets the feedback immediately and in the right place. In everyday work, this happens in five places of a component: the props, the state, the event handlers, the refs, and the types you derive from existing data structures. You rarely need more, and the rest of this article walks through the five one by one.
The core: errors move forward#
Before we write code, it pays to make the difference in the flow clear. Without types, the app builds no matter what I put into a prop – the error only happens at runtime, when someone uses the page. With types, the compiler checks the JSX usage against the interface, and the error appears before anything is built.
flowchart TD
A[Wrong prop in JSX] --> B{TypeScript active?}
B -->|No| C[App builds]
C --> D[Runtime error<br/>for the user in the browser]
B -->|Yes| E[tsc / editor checks<br/>against the interface]
E --> F[Compile error<br/>red in the editor]
F --> G[Fix before the commit]The left path costs you a bug report, in the worst case an annoyed customer. The right path costs you ten seconds. This shift forward is the real gain – not autocompletion, as nice as it is.
The UI boundary is the most expensive boundary#
Before getting into the details, it pays to name the place where the effort pays off the most. Every component has a boundary: props flow in, events flow out. This boundary is exactly the seam where two pieces of code meet – often two authors, sometimes two teams. A form that expects an onSubmit, a table that reports a row upward through a callback, a design system button that five feature teams consume: these are not internal implementation details, they are interfaces. And interfaces are where the expensive errors come from, because the error happens on one side and shows up on the other.
A type at this boundary is an executable contract. “Executable” means: it is not a comment someone has to maintain, and not a line on a wiki page nobody reads. The compiler runs it every time you save. When I change a button’s props signature, the tool points me, right there, to each of the five call sites that no longer fit – before anyone starts the app. The contract is thus the documentation, the test and the refactoring safety net of this boundary at the same time, in exactly one artifact.
The trade-off is real and deserves to be said out loud. Types cost typing, they have to be kept current, and in a poorly chosen place they create friction instead of safety. Deciding where to put them is therefore a cost-benefit question. The more consumers a component has, the longer it lives and the more people pass through it, the more clearly the contract pays off – a shared UI building block deserves precise props and event types. A throwaway prototype or a purely internal helper component with a single caller hardly deserves one. The rule of thumb: type the boundaries where responsibilities meet, and let inference handle the rest. Not every local variable needs a contract, but every props and event signature that someone else calls becomes one.
Props as a contract: interface or type#
The start is unspectacular, and that is exactly why it holds up so well. A component is a function, its props are an object, and that object gets a type.
interface ButtonProps {
label: string;
disabled?: boolean;
}
function Button({ label, disabled }: ButtonProps) {
return <button disabled={disabled}>{label}</button>;
}
The ? after disabled makes the prop optional. If someone forgets label, the compiler reports a missing required prop – not an undefined that later ends up as an empty button, but an error right where it happens.
In code reviews, this is where the question reliably comes up: interface or type? Both work for props, and the pragmatic rule of thumb from the React TypeScript Cheatsheet is: “interface until you need type.” In other words:
interfacesupports declaration merging, which is handy for public library APIs, and reads a bit more naturally for simple object shapes.typeis the right choice as soon as you need union types, mapped types or compositions of several types – things aninterfacecannot express.
For 90 percent of component props, the choice is purely a matter of taste. What matters is consistency in the team, not the debate over principles.
children is no longer automatic#
As soon as a component wraps other elements, it needs children. And this is worth a close look, because something fundamental changed with version 18 of @types/react: the implicit children declaration was removed. React.FC used to bring an automatic children along. Today you have to declare it yourself if your component renders children.
interface CardProps {
title: string;
children?: React.ReactNode;
}
function Card({ title, children }: CardProps) {
return (
<section className="card">
<h2>{title}</h2>
<div className="card-body">{children}</div>
</section>
);
}
React.ReactNode is the right type for “anything that can be rendered”: strings, numbers, elements, arrays of those, null, boolean. If instead you want to enforce exactly one single element, you reach for React.ReactElement. By the way, in the version 18 types, the JSX namespace lives under React.JSX, so a single element can also be described as React.JSX.Element. For everyday work, ReactNode is almost always enough – it is deliberately generous.
The fact that children no longer appears by magic is one of the reasons React.FC has lost importance. More on that shortly.
Typing state: when inference is enough and when it isn’t#
useState is a nice example of how TypeScript doesn’t demand manual work everywhere. Most of the time, the compiler infers the type from the initial value:
const [count, setCount] = useState(0); // number
const [name, setName] = useState(''); // string
const [open, setOpen] = useState(false); // boolean
Adding a generic here would just be ballast. The inference is unambiguous, and setCount('drei') still fails at the compiler. It gets interesting when the initial value tells the compiler too little. I have fixed this pitfall in existing code many times:
// Wrong: type is inferred as `null`
const [user, setUser] = useState(null);
// later setUser({ id: 1, name: 'Mike' }) -> compile error
// Correct: specify the generic explicitly
const [user, setUser] = useState<User | null>(null);
If you start with null, TypeScript infers the type null – and then you can never write anything else into it. The same happens with useState([]), which becomes never[], or with an empty object. The rule I have adopted for this: if the initial value is empty, null or an empty array, specify the type with the generic.
const [items, setItems] = useState<string[]>([]);
const [selected, setSelected] = useState<User | null>(null);
Typing events: no more any#
The next classic is event handlers. In JavaScript, you write onChange={(e) => setValue(e.target.value)} and don’t think further. In TypeScript, e without a type is an any – and any is the hole through which exactly the errors we wanted to get rid of come back. React ships precise types for its synthetic events. You just have to pick the right one.
function LoginForm() {
const [email, setEmail] = useState('');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log('submitting', email);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={handleChange} />
<button type="submit">Sign in</button>
</form>
);
}
Two things matter here. First, the generic has to match the element: an <input> yields HTMLInputElement, and only then is e.target.value known at all. If you accidentally write HTMLElement, you lose value. Second, there are matching types for onChange, onSubmit and onClick:
React.ChangeEvent<HTMLInputElement>for inputs, and likewiseHTMLSelectElementandHTMLTextAreaElement.React.FormEvent<HTMLFormElement>for submitting a form.React.MouseEvent<HTMLButtonElement>for clicks.
If you define the handler inline, directly on the JSX attribute, you can often skip the type, because React infers it from the context. But as soon as you pull the handler out into a separate function, you have to specify the event type yourself. For props that take a handler, there are also the shorthands React.ChangeEventHandler<HTMLInputElement> and React.FormEventHandler<HTMLFormElement> – handy when you pass a callback down as a prop.
useRef: DOM reference with a null check#
useRef is confusing at first because it plays two roles. The most common one is the DOM reference, for example to focus a field on mount.
function SearchBox() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} type="search" />;
}
Three details count. The generic <HTMLInputElement> says what the ref points to. The initial value null is intentional: before the first render, the DOM element doesn’t exist yet. This combination produces a read-only RefObject, and that is exactly what fits the JSX attribute ref. Because current can be null before mounting, you need a null check on access – hence the ?. in inputRef.current?.focus(). Without the guard, the compiler rightly complains.
The second role of useRef is that of a mutable instance variable that doesn’t trigger a re-render – for example, to hold on to a timer ID or a previous value:
const timerRef = useRef<number | null>(null);
const start = () => {
timerRef.current = window.setTimeout(() => {
console.log('done');
}, 1000);
};
Here current is writable. The difference comes from the overload: with null in the union type and no DOM reference, you get a MutableRefObject. You don’t have to memorize this subtlety, but it helps to know that the DOM case is deliberately read-only.
Utility types: derive props instead of copying them#
When data structures grow, you don’t want to update props by hand in three places. That is what the utility types from the TypeScript standard library are for – not from React, but constantly useful in everyday React work. Suppose there is a User:
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'member';
}
A form that only edits name and email doesn’t need the whole User. Pick cuts out the relevant fields:
type EditUserProps = Pick<User, 'name' | 'email'>;
Conversely, Omit removes what you don’t want – for example, the server-assigned id:
type NewUserProps = Omit<User, 'id'>;
Partial makes all fields optional, which fits patch operations or intermediate form states:
type UserDraft = Partial<User>;
The gain: if User changes, the derived types follow automatically. No field gets out of step. Besides Pick, Omit and Partial, Required<T> and Readonly<T> belong to the standard repertoire.
A React-specific trick rounds out the picture: if your component should inherit the native props of an HTML element – all standard button attributes, for example – you use React.ComponentPropsWithoutRef:
type IconButtonProps = React.ComponentPropsWithoutRef<'button'> & {
icon: string;
};
function IconButton({ icon, ...rest }: IconButtonProps) {
return (
<button {...rest}>
<span className="icon">{icon}</span>
</button>
);
}
This way you get onClick, disabled, type and all the other button attributes for free and type-checked, without listing them one by one.
Everyday types at a glance#
This overview shows the five corners where you deal with types most often in a typed React component.
graph TD
K[Types in everyday React] --> P[Props<br/>interface / type]
K --> S[State<br/>useState<T>]
K --> E[Events<br/>ChangeEvent / FormEvent]
K --> R[Refs<br/>useRef<HTMLInputElement>]
K --> U[Derivation<br/>Pick / Omit / Partial]
P --> C[children:<br/>ReactNode]These five cover most of the daily work. Everything else builds on them.
And what about React.FC?#
The question is guaranteed to come up, often with a code example from an older tutorial: const Button: React.FC<ButtonProps> = (props) => .... Is that wrong? No. It works, it is available in 2024, and nobody has to rewrite existing code. But the modern default is the plain function with typed props, and there are reasons for that.
Historically, the most important one was the implicit children that React.FC brought along – components accepted children even when they weren’t supposed to render any. With @types/react 18, this implicit children was removed, which defused one of the main points of criticism. What remains is mainly that React.FC gets in the way of generic components. If you want to write a type-safe list component over an arbitrary element type, you are better off with a normal function:
interface ListProps<T> {
items: T[];
render: (item: T) => React.ReactNode;
}
function List<T>({ items, render }: ListProps<T>) {
return <ul>{items.map((item, i) => <li key={i}>{render(item)}</li>)}</ul>;
}
Something like this is awkward to express with React.FC. So today React.FC is a question of style, not a mistake. Pick one variant in your team and stick with it. I write normal functions myself, because they are more flexible with generics and come with fewer special rules.
Coming back to hooks#
If you already write your own hooks, you quickly notice that the building blocks shown here carry straight over: a custom hook returns typed state, takes typed arguments and encapsulates event logic. If you haven’t taken the path to reusable logic yet, have a look at From HOCs and Render Props to Custom Hooks – the typing from this article is exactly what turns a custom hook from a loose collection of functions into a clear contract.
Conclusion#
The gain of TypeScript in React can be summed up in four effects, and none of them is in the API documentation. Shorter cycles, because an integration error shows up in the editor in seconds instead of in days via a bug report. Less friction at the most expensive place, the boundary between components and teams, because the contract automatically checks what would otherwise be agreed on verbally and then forgotten. Higher quality, because a wrong prop type, a forgotten required field or a null that should never have stayed null never makes it into the build in the first place. And clear boundaries, because a typed props and event signature says unambiguously what goes in and what comes out.
Getting started is manageable. Props as interface or type, children declared explicitly as ReactNode, useState with a generic only where inference is too narrow, the matching event types instead of any, useRef with a null check, and utility types to derive props instead of copying them. These six moves cover everyday work. Everything beyond that – generic components, complex unions, your own hooks – continues the same idea: type the boundaries where responsibilities meet, say clearly what you expect, and let the compiler make sure everyone sticks to it.
Further reading#
- React TypeScript Cheatsheet: react-typescript-cheatsheet.netlify.app and the repository github.com/typescript-cheatsheets/react
- react.dev – “Using TypeScript”: react.dev/learn/typescript
- react.dev – hooks reference: useState and useRef
- TypeScript Handbook – Utility Types: typescriptlang.org/docs/handbook/utility-types.html
- DefinitelyTyped –
@types/react: github.com/DefinitelyTyped/DefinitelyTyped
Revised and translated from German with the help of AI.