React with TypeScript
Typing props, state, events, and components for type-safe React applications.
What you'll learn
- Typing component props with interfaces and types
- Typing useState, useRef, and event handlers
- Using React.FC and alternative typing approaches
- Typing context, refs, and generic components
Concept
Why TypeScript with React?
TypeScript adds static type checking to JavaScript, catching errors at compile time before they reach the browser. In React, this means you get type safety for props (a parent cannot pass the wrong type to a child), autocomplete for component APIs, and self-documenting code. When you rename a prop, the compiler tells you every place that needs updating. For any project beyond a prototype, TypeScript is the recommended choice and is the default in frameworks like Next.js and Create React App's TypeScript template.
Typing Props
Define an interface or type alias for your component's props and use it as the generic parameter: function UserCard({ name, age }: UserCardProps) {}. For children, use React.ReactNode. For event handlers, use the specific React event types: React.ChangeEvent<HTMLInputElement> for input changes, React.MouseEvent<HTMLButtonElement> for button clicks. These types give you autocomplete for event properties and prevent accessing non-existent properties.
Typing Hooks
useState infers the type from the initial value. For complex types or when the initial value is null, provide a generic: useState<User | null>(null). useRef needs a generic when the ref is used for a DOM element: useRef<HTMLInputElement>(null). useContext infers the type from the context's creation. For useReducer, type the state and action union type to get exhaustive switch checking.
React.FC and Alternatives
React.FC (formerly React.FunctionComponent) is a type for function components, but it is no longer recommended as the default. It implicitly adds children to props (which you may not want) and has subtle differences with default props. The preferred approach is to type the props directly in the function signature: function MyComponent(props: MyProps): JSX.Element {}. This is more explicit and gives you better control.
Utility Types for Props
TypeScript provides utility types that are useful for component props. Partial<T> makes all props optional. Pick<T, Keys> selects specific props from a type. Omit<T, Keys> removes specific props. ComponentProps<typeof Component> extracts the props type of an existing component. These let you build prop types from existing ones without duplication, keeping your types DRY and maintainable.
Example
import { useState, useRef, createContext, useContext } from "react";
// Type the props with an interface.
interface UserCardProps {
name: string;
age: number;
role?: "admin" | "user"; // Optional union type.
onSelect?: (id: number) => void;
}
function UserCard({ name, age, role = "user", onSelect }: UserCardProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [isEditing, setIsEditing] = useState<boolean>(false);
// Type the event handler with the specific React event type.
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
return (
<div>
<h3>{name} ({age}) — {role}</h3>
<input ref={inputRef} onChange={handleChange} />
{onSelect && <button onClick={() => onSelect(1)}>Select</button>}
</div>
);
}
// Typed context.
interface ThemeContextType {
theme: "light" | "dark";
toggle: () => void;
}
const ThemeContext = createContext<ThemeContextType | null>(null);
function useTheme(): ThemeContextType {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
return ctx;
}
Props are typed with an interface, including optional and union types. Event handlers use specific React event types. useRef and createContext use generics for type safety.
Try it
- JSON Formatter
TypeScript interfaces often mirror JSON shapes — format to compare.
- Code Diff
Compare type definitions when refactoring component APIs.
Common mistakes
The mistake
Using React.FC for all components by default
The fix
React.FC implicitly adds children to props and has quirks with generics and default props. Prefer typing props directly in the function signature: function MyComponent(props: MyProps) {}. It is more explicit and flexible.
The mistake
Using 'any' for event types instead of specific React event types
The fix
Use React.ChangeEvent<HTMLInputElement>, React.MouseEvent<HTMLButtonElement>, etc. These give you autocomplete and type checking for event properties. 'any' defeats the purpose of TypeScript.
Practice React with TypeScript
1 exercise
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.