TypeScript with React
TypeScript with React is a common pairing in modern web development. React builds the user interface, and TypeScript checks that your props, state, and event handlers use the right types. This catches bugs before you open the browser. In real projects, typed components make refactoring safer and give strong autocomplete in the editor.
This tutorial shows you how to create a React + TypeScript project with Vite, type component props, handle optional and default props, type children, useState and useRef, handle events like ChangeEvent and MouseEvent, type fetched data, and build a small generic list component. Each example is complete and compiles under strict mode.
How Do You Create a React + TypeScript Project?
The fastest way to start is with Vite, a modern build tool. You can use npm create vite@latest to generate a project. Pick the react-ts template and Vite sets up React, TypeScript, and a tsconfig.json with strict mode ready.
Here is the setup:
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev
You should see a starter page at localhost:5173. Open src/App.tsx and you can start writing typed components.
How Do You Type React Component Props?
A prop is data passed into a component from its parent. In TypeScript, you define an interface that describes each prop's type. The component function receives an object of that shape, so the compiler checks every prop at every call site.
interface GreetingProps {
name: string;
age: number;
}
function Greeting({ name, age }: GreetingProps) {
return <p>{name} is {age} years old.</p>;
}
// Usage in App:
// <Greeting name="Riya" age={28} />
// Output in the browser: Riya is 28 years old.
How it works: The GreetingProps interface declares name and age. The component destructures them. If you call <Greeting name="Riya" /> without age, the compiler reports a missing prop error. If you pass age="28" as a string, the compiler rejects it too. This is the core pattern for every typed component.
How Do Optional and Default Props Work?
An optional prop uses ? in the interface and may be missing at the call site. A default prop provides a fallback value using a destructuring default. Optional props get undefined in their type, so a default handles the missing case cleanly.
interface ButtonProps {
label: string;
variant?: "primary" | "secondary";
disabled?: boolean;
}
function Button({ label, variant = "primary", disabled = false }: ButtonProps) {
return (
<button className={variant} disabled={disabled}>
{label}
</button>
);
}
// <Button label="Save" /> uses both defaults
// <Button label="Cancel" variant="secondary" disabled />
// Output: a styled button with the given label
How it works: variant and disabled are optional, so callers may skip them. The destructuring defaults "primary" and false fill in when the prop is undefined. The variant type is a literal union, so passing "danger" is a compile error. This gives you a small, safe API for each component.
How Do You Type children?
The children prop is the content between the opening and closing tags. Its type is usually React.ReactNode, which accepts strings, numbers, JSX elements, arrays, and null. Use ReactNode for flexible wrappers like layouts and cards.
import type { ReactNode } from "react";
interface CardProps {
title: string;
children: ReactNode;
}
function Card({ title, children }: CardProps) {
return (
<div className="card">
<h3>{title}</h3>
{children}
</div>
);
}
// <Card title="Welcome"><p>Hello</p></Card>
// Output: a card with the title and the paragraph inside
How it works: The children prop is typed as ReactNode, so the component accepts almost any renderable content. If you typed it as string, the JSX child <p>Hello</p> would fail. Use ReactNode for generic wrappers and a narrower type when you need specific children.
How Do You Type useState and useRef?
useState is a hook, a function that adds state to a function component. TypeScript infers the state type from the initial value. When the initial value is null or a union, pass the type explicitly with <Type>. useRef holds a mutable reference, and its type is useRef<Type>(initial).
import { useState, useRef } from "react";
interface User {
id: number;
name: string;
}
function UserPanel() {
const [user, setUser] = useState<User | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
function loadUser() {
setUser({ id: 1, name: "Riya" });
}
function focusInput() {
inputRef.current?.focus();
}
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
<button onClick={loadUser}>Load</button>
<p>{user ? user.name : "No user"}</p>
</div>
);
}
// Output initially: "No user"
// After clicking Load: "Riya"
How it works: useState<User | null>(null) says the state is a User or null. That lets the component render a fallback before data arrives. useRef<HTMLInputElement>(null) says the ref will point to an input element. inputRef.current?.focus() uses optional chaining because current may be null before the element mounts. Without the explicit type on useRef, current would be null forever, and .focus() would fail.
How Do You Type Event Handlers?
Event handlers like onChange and onClick receive event objects. TypeScript types them with React.ChangeEvent<HTMLInputElement> and React.MouseEvent<HTMLButtonElement>. The generic parameter is the element type, which gives you accurate properties like value or currentTarget.
import { useState } from "react";
import type { ChangeEvent, MouseEvent } from "react";
function SearchForm() {
const [query, setQuery] = useState("");
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setQuery(event.target.value);
}
function handleClick(event: MouseEvent<HTMLButtonElement>) {
event.preventDefault();
console.log(`Searching for: ${query}`);
}
return (
<form>
<input value={query} onChange={handleChange} />
<button onClick={handleClick}>Search</button>
</form>
);
}
// Output in the console when clicking: Searching for: <query>
How it works: ChangeEvent<HTMLInputElement> types the event so event.target.value is a string. If you typed the parameter as a plain Event, the compiler would not know about target.value. MouseEvent<HTMLButtonElement> gives access to button-specific properties and preventDefault. Use the correct generic so the event object is useful inside the handler.
How Do You Type a Fetch Result?
When you fetch data from an API, the response starts as unknown. You should validate it or cast it after checking the shape. Then useState<User | null> stores the parsed result and renders it safely.
import { useState, useEffect } from "react";
interface User {
id: number;
name: string;
}
function UserLoader() {
const [user, setUser] = useState<User | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function load() {
try {
const response = await fetch("/api/user/1");
const data: unknown = await response.json();
if (typeof data === "object" && data !== null && "name" in data) {
setUser(data as User);
} else {
setError("Invalid response");
}
} catch {
setError("Network error");
}
}
load();
}, []);
if (error) return <p>{error}</p>;
return <p>{user ? user.name : "Loading..."}</p>;
}
// Output: "Loading..." then the user name when data arrives
How it works: response.json() returns any, so we store it as unknown to keep safety. The check verifies the object has a name field before casting. useState<User | null> models the loading state. useState<string | null> models the error. The component renders the right branch based on those states. This is the standard fetch pattern in typed React code.
How Do You Build a Generic List Component?
A generic component takes a type parameter so it can render any item type. Write <T,> with a trailing comma in .tsx files so the parser does not confuse it with JSX. Then type the items array and the renderItem callback with T.
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T,>({ items, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);
}
// <List items={["a", "b"]} renderItem={(s) => <b>{s}</b>} />
// <List items={[1, 2]} renderItem={(n) => <i>{n}</i>} />
// Output: a list of rendered items
How it works: The List component is generic over T. When you pass items={["a", "b"]}, T becomes string, so renderItem receives a string. When you pass numbers, T is number. The trailing comma after T is required in .tsx files to tell the parser this is a type parameter, not a JSX tag. This pattern works for tables, dropdowns, and any repeated UI.
React.FC vs Plain Function Components: Which Should You Use?
| Feature | React.FC | Plain function |
|---|---|---|
Types children automatically |
Yes (older versions) | No, type it yourself |
| Works with generics | Awkward | Yes, straightforward |
| Default props clarity | Less clear | Clear with destructuring defaults |
| Recommended today | Not preferred | Yes |
The recommendation is to use a plain function component with a props interface. React.FC is still supported, but it adds an implicit children type that can hide mistakes, and it complicates generic components. Plain functions are simpler and align with modern React guidance. You can learn more about interfaces in the TypeScript Interfaces tutorial.
Common Mistakes and Best Practices
- Typing event handlers with
any. This loses the element type and hides bugs like readingvaluefrom a button. Always useChangeEvent<HTMLInputElement>,MouseEvent<HTMLButtonElement>, or the correct generic for the target element. - Forgetting the explicit type on
useStatewhen starting withnull.useState(null)infersnulland never allows a user object. WriteuseState<User | null>(null)so the setter accepts aUser. - Using
React.FCwith generics.React.FCdoes not compose well with type parameters and can make the generic list component harder to write. Use a plain function and a props interface instead. - Missing the trailing comma in generic
.tsxcomponents.<T>is parsed as JSX in.tsxfiles. Write<T,>to make it a type parameter. This is a common and confusing syntax error. - Casting
response.json()directly to a type. The data may not match, and the cast hides the problem. Store it asunknown, check the shape, then narrow or cast.
Real-World Example: Typed Button, Form Input, and User State
This example combines a typed Button component, a form input with ChangeEvent<HTMLInputElement>, and useState<User | null>.
import { useState } from "react";
import type { ChangeEvent } from "react";
interface User {
id: number;
name: string;
}
interface ButtonProps {
label: string;
onClick: () => void;
variant?: "primary" | "secondary";
}
function Button({ label, onClick, variant = "primary" }: ButtonProps) {
return (
<button className={variant} onClick={onClick}>
{label}
</button>
);
}
function UserForm() {
const [name, setName] = useState("");
const [user, setUser] = useState<User | null>(null);
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setName(event.target.value);
}
function handleSave() {
if (name.trim() === "") return;
setUser({ id: Date.now(), name });
}
return (
<div>
<input value={name} onChange={handleChange} placeholder="Your name" />
<Button label="Save" onClick={handleSave} />
<Button label="Clear" variant="secondary" onClick={() => setName("")} />
<p>{user ? `Saved: ${user.name}` : "No user saved"}</p>
</div>
);
}
// Output initially: "No user saved"
// After typing and clicking Save: "Saved: <name>"
How it works, line by line. The User interface models the saved data. ButtonProps types the button with a required label and onClick and an optional variant that defaults to "primary". Button renders a styled button and passes the click through. In UserForm, useState("") infers string for name, and useState<User | null>(null) models the saved user. The handleChange function uses ChangeEvent<HTMLInputElement> so event.target.value is a string. handleSave guards against empty input and creates a user with a timestamp ID. The JSX renders the input, two buttons, and the status line. The Clear button uses an inline arrow for a simple reset. Every prop and event is checked at compile time, so a wrong label type or a missing onClick is caught before the browser runs the code. The TypeScript Generics tutorial explains the type-parameter machinery behind the generic list component.
Summary
- TypeScript with React adds type safety to props, state, events, and data, catching bugs before runtime.
- Create a project with
npm create vite@latestand thereact-tstemplate to get strict TypeScript set up. - Type props with an interface; use
?for optional props and destructuring defaults for defaults. - Type
childrenasReactNode, and useuseState<User | null>for nullable state. - Use
ChangeEvent<HTMLInputElement>andMouseEvent<HTMLButtonElement>for accurate event types. - Generic components with
<T,>handle any item type, and plain function components are preferred overReact.FC.
Now that you can type React components, continue to the TypeScript with Node.js tutorial to learn how to build typed backends with Express and Node.
Frequently Asked Questions
Should I use React.FC for my components?
Most modern React teams do not. React.FC adds an implicit children type in older versions, complicates generics, and makes default props less clear. Use a plain function with a props interface and destructure the props. You can still type children explicitly as ReactNode when the component needs it.
How do I type useState when the initial value is null?
Pass the type explicitly: useState<User | null>(null). Without it, TypeScript infers null, and the setter only accepts null. The explicit union allows both null and User, so you can start empty and fill in data later. This is the standard pattern for fetched data.
Why do I need a trailing comma in <T,> for generic components?
In .tsx files, the parser treats <T> as the start of a JSX tag. Adding a trailing comma, <T,>, tells the parser this is a type parameter list, not JSX. Without it, you get a syntax error. This rule applies to arrow functions and function declarations in .tsx files.
How do I type an onClick handler?
Use MouseEvent<HTMLButtonElement> for a button click. Import the type from React: import type { MouseEvent } from "react". The generic parameter is the element the handler is attached to, which gives you correct properties like currentTarget. If you do not need the event, you can type the handler as () => void.
Can I use TypeScript with React without a build tool?
You can, but it is not practical for most projects. React uses JSX, which browsers do not understand, so a build step is needed to transform JSX and TypeScript into JavaScript. Vite, Next.js, and Create React App all handle this. Use one of them for a smooth setup.
Practice Exercises
Exercise 1 (Easy): Type a Button Component
Create a Button component with props label: string, onClick: () => void, and an optional disabled?: boolean. Render a button.
Show solution
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
function Button({ label, onClick, disabled = false }: ButtonProps) {
return (
<button onClick={onClick} disabled={disabled}>
{label}
</button>
);
}
// <Button label="Save" onClick={() => console.log("saved")} />
// <Button label="Cancel" onClick={() => {}} disabled />
// Output: a button with the given label and state
The props interface types each field, and the destructuring default sets disabled to false when omitted.
Exercise 2 (Easy): Type a ChangeEvent
Create an input component with useState("") and a handleChange typed as ChangeEvent<HTMLInputElement>. Print the typed value.
Show solution
import { useState } from "react";
import type { ChangeEvent } from "react";
function NameInput() {
const [name, setName] = useState("");
function handleChange(event: ChangeEvent<HTMLInputElement>) {
setName(event.target.value);
}
return (
<div>
<input value={name} onChange={handleChange} />
<p>{name}</p>
</div>
);
}
// Output: the paragraph mirrors what you type
The ChangeEvent<HTMLInputElement> type makes event.target.value a string, which matches the useState("") type.
Exercise 3 (Medium): useState with a Union Type
Create a component with useState<User | null>(null) where User has id and name. Add a button that sets a user and a paragraph that shows the name or "No user".
Show solution
import { useState } from "react";
interface User {
id: number;
name: string;
}
function UserPanel() {
const [user, setUser] = useState<User | null>(null);
return (
<div>
<button onClick={() => setUser({ id: 1, name: "Riya" })}>Load</button>
<p>{user ? user.name : "No user"}</p>
</div>
);
}
// Output initially: "No user"
// After clicking Load: "Riya"
The union type lets the state start as null and later hold a User, which is the standard pattern for async data.
Exercise 4 (Challenge): Generic List Component
Create a generic List<T,> component with items: T[] and renderItem: (item: T) => React.ReactNode. Use it with a string array and a number array.
Show solution
import type { ReactNode } from "react";
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
function List<T,>({ items, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);
}
// <List items={["a", "b"]} renderItem={(s) => <b>{s}</b>} />
// <List items={[1, 2]} renderItem={(n) => <i>{n}</i>} />
// Output: two lists, one bold and one italic
The trailing comma in <T,> is required in .tsx files, and the generic keeps renderItem in sync with the item type.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
