ReactAdvanced

React with TypeScript: Typing Props, State and Events

Master React with TypeScript: type components, props, state, event handlers, and custom hooks with compile-time type safety using the react-ts template.

React CourseLesson 55 of 66 (83% complete)
All React lessons (66)View curriculum

What you will learn

In JavaScript, misspelling a prop name (like writing title instead of headline) or passing an object instead of an array fails silently until the app runs in the browser and throws a runtime exception. In large professional teams, catching these mistakes before running the code saves hours of debugging.

TypeScript adds static types to JavaScript, providing autocomplete, instant inline documentation, and build-time verification.

In Build Along: Notes CRUD App, you built a full interactive CRUD application using vanilla JavaScript. In this lesson, you will learn how to make that codebase rock-solid with TypeScript static types:

  • How to set up a Vite React app with the react-ts template.
  • How to define clean TypeScript types and interfaces for component props (including children and optional props).
  • How TypeScript infers and types useState, useReducer, and useRef.
  • How to correctly type browser events (onClick, onChange, onSubmit).
  • How to type custom hooks and reusable generic components safely.

Creating a Vite React TypeScript Project

To create a new React app with TypeScript support out of the box:

npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
npm install
npm run dev

Notice the file extensions:

  • Files with JSX use .tsx (e.g. App.tsx, Button.tsx).
  • Pure utility or logic files use .ts (e.g. api.ts, types.ts).

Typing Component Props

In TypeScript, you describe the shape of your props using an interface or type:

// UserCard.tsx
interface UserCardProps {
  name: string;
  age: number;
  email: string;
  role?: "admin" | "editor" | "viewer"; // Optional union type
  onSelect?: (userId: string) => void;  // Callback function
}

export function UserCard({ name, age, email, role = "viewer", onSelect }: UserCardProps) {
  return (
    <div className={`user-card role-${role}`}>
      <h3>{name} ({age})</h3>
      <p>{email}</p>
      {onSelect && (
        <button onClick={() => onSelect(email)}>Select Profile</button>
      )}
    </div>
  );
}

If another developer attempts to write <UserCard name="Alex" age="twenty" />, their IDE immediately highlights age in red with:

Type 'string' is not assignable to type 'number'.

Typing children

When building container or layout wrappers, type children with React.ReactNode:

import type { ReactNode } from 'react';

interface CardWrapperProps {
  title: string;
  children: ReactNode; // Accepts JSX, strings, numbers, fragments, or null
}

export function CardWrapper({ title, children }: CardWrapperProps) {
  return (
    <div className="card">
      <header className="card-header">
        <h2>{title}</h2>
      </header>
      <div className="card-body">
        {children}
      </div>
    </div>
  );
}

Typing Hooks

TypeScript’s type inference handles most React hooks automatically, but some require explicit generic types.

1. useState

When initializing with primitive values, TypeScript infers the type automatically:

const [count, setCount] = useState(0); // Inferred as number
const [name, setName] = useState("");   // Inferred as string

When initializing with null before data arrives from an API:

interface User {
  id: string;
  username: string;
}

// Explicit generic parameter: User or null
const [user, setUser] = useState<User | null>(null);

// Later in your JSX:
// user.username  TS Error: 'user' is possibly 'null'
// user?.username  Safe navigation

2. useRef

When referencing DOM elements, provide the specific HTML element interface and initialize with null:

import { useRef } from 'react';

function SearchInput() {
  // Specifically types the ref as an HTMLInputElement
  const inputRef = useRef<HTMLInputElement>(null);

  function focusField() {
    inputRef.current?.focus();
  }

  return <input ref={inputRef} type="search" />;
}

3. useReducer

Combine TypeScript discriminated unions with reducers for unbeatable state safety:

interface State {
  count: number;
}

// Discriminated union of allowed actions
type Action =
  | { type: "increment" }
  | { type: "decrement" }
  | { type: "reset"; payload: number };

function counterReducer(state: State, action: Action): State {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: action.payload }; // TypeScript knows payload exists here!
    default:
      return state;
  }
}

If you accidentally dispatch { type: "unknown" }, TypeScript flags it at compile time.

Typing Form and Mouse Events

When attaching inline handlers, TypeScript automatically knows what event is:

<input onChange={(e) => console.log(e.target.value)} />

When extracting the handler to a named function, annotate the event with React’s event types from 'react':

import type { ChangeEvent, FormEvent, MouseEvent } from 'react';

export function ContactForm() {
  function handleTextChange(event: ChangeEvent<HTMLInputElement>) {
    console.log(event.target.value);
  }

  function handleButtonClick(event: MouseEvent<HTMLButtonElement>) {
    console.log("Clicked at coordinates:", event.clientX, event.clientY);
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    console.log("Form submitted safely");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" onChange={handleTextChange} />
      <button type="submit" onClick={handleButtonClick}>Send</button>
    </form>
  );
}

Quick Event Reference:

  • ChangeEvent<HTMLInputElement>: Text inputs, checkboxes, radios.
  • ChangeEvent<HTMLSelectElement>: <select> dropdowns.
  • ChangeEvent<HTMLTextAreaElement>: <textarea> multiline text.
  • FormEvent<HTMLFormElement>: Form submit events.
  • MouseEvent<HTMLButtonElement>: Button clicks.
  • KeyboardEvent<HTMLInputElement>: Keydown and keyup events.

Typing Custom Hooks

When a custom hook returns an array tuple (like useState), tell TypeScript it is a constant tuple using as const:

import { useState } from 'react';

export function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue((v) => !v);

  // 'as const' ensures TS infers [boolean, () => void] instead of (boolean | () => void)[]
  return [value, toggle] as const;
}

Common mistakes

1. Using any whenever a type error occurs

Using const [data, setData] = useState<any>(null) disables TypeScript’s safety features entirely. Define real interfaces for your API models.

2. Typing children as JSX.Element

JSX.Element only accepts a single JSX tag. It rejects plain strings, numbers, arrays, and null. Always prefer React.ReactNode for children.

3. Forgetting the HTML prefix on event targets

Writing ChangeEvent<InputElement> is a syntax error. Native DOM element types are prefixed with HTML: HTMLInputElement, HTMLDivElement, HTMLButtonElement.

Practice

  1. Create a Button component in .tsx that accepts variant?: 'primary' | 'secondary' | 'danger', disabled?: boolean, and onClick: () => void.
  2. Build an interface TodoItem with id: number, title: string, and completed: boolean. Build a TodoList component that accepts items: TodoItem[].
  3. Create a custom input component with an inputRef = useRef<HTMLInputElement>(null). Add a button that selects all text using inputRef.current?.select().
  4. Type a login form with ChangeEvent<HTMLInputElement> on email/password fields and FormEvent<HTMLFormElement> on submit.
  5. Create a generic list component function List<T>({ items, renderItem }: ListProps<T>) that can render arrays of any type.
  6. Run npm run build in your TypeScript project and verify that the TypeScript compiler (tsc) catches type errors before generating the bundle.

Recap

  • TypeScript catches bugs at build time, provides auto-completion, and serves as living documentation.
  • Use interface or type to describe component props and callback signatures.
  • Type children using React.ReactNode.
  • Generic hooks like useState<User | null>(null) and useRef<HTMLInputElement>(null) ensure safe DOM and state operations.
  • Annotate event handlers with ChangeEvent<HTMLInputElement> or FormEvent<HTMLFormElement>.
  • In the next lesson, you will learn how to write automated component tests with Vitest and React Testing Library!

Frequently asked questions

Should I use interface or type for React props?

Both work well. In general, interface is preferred for component props because it produces clean error messages and supports declaration merging. type is preferred for unions (e.g. 'small' | 'large') and tuple returns.

Do I need to import React in every .tsx file with TypeScript?

No. Modern TypeScript with "jsx": "react-jsx" in tsconfig.json uses the automatic JSX runtime, so import React from 'react' is not required unless you are using React namespace members.

How do I type HTML attributes like className and style on custom components?

Extend React’s built-in component prop types: interface MyBtnProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { customVariant?: string; }. Your button will automatically inherit className, id, disabled, and standard HTML attributes.

Does TypeScript slow down my production app in the browser?

Zero slowdown. TypeScript types are completely stripped away during the Vite build process. The browser runs 100% clean, standard JavaScript.

Can I migrate an existing JavaScript React app to TypeScript gradually?

Yes! TypeScript allows you to rename files one by one from .jsx to .tsx. You can type your core components first and migrate secondary pages over time.

See also: React Project Structure, React Props, Handling Events in React