How Do You Use TypeScript with React Components?

Learn How Do You Use TypeScript with React Components? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Type-Safe React

React is a JavaScript library for building user interfaces, while TypeScript adds static type checking to JavaScript. Using them together helps developers catch incompatible props, invalid state updates, incorrect event handling, and other common mistakes during development.

In a React application, components exchange data through props, manage changing values through state, respond to user events, and often communicate with APIs. TypeScript allows these interactions to be described through interfaces, type aliases, generics, and other type system features.

For example, a course card might require a numeric course identifier, a string title, and a boolean indicating whether the course is published. A typed component can enforce these requirements wherever the card is used.

TypeScript does not replace React's runtime behavior or validate arbitrary external data automatically. Instead, it improves the development experience by checking that your code follows the contracts you define. Runtime validation is still necessary for API responses and other untrusted values.

1. Setting Up React with TypeScript

A React project can be created with a TypeScript-ready template using a modern build tool such as Vite. The following command creates a React application with TypeScript support.

npm create vite@latest my-react-app -- --template react-ts

cd my-react-app

npm install

npm run dev

In a TypeScript React project, components commonly use the .tsx extension because their source files contain JSX. Ordinary TypeScript files that do not contain JSX usually use the .ts extension.

For example, a component might be stored in src/components/CourseCard.tsx, while shared data types could be stored in src/types/course.ts.

The TypeScript compiler and the project's build tools work together to process the application. The exact type-checking command depends on the project's scripts and build configuration, so inspect package.json rather than assuming that every build command performs the same checks.

2. Typing React Component Props

Props allow a parent component to pass data to a child component. Defining a props interface documents the required values and helps TypeScript detect invalid component usage.

interface CourseCardProps {
  title: string;
  duration: number;
  isPublished: boolean;
}

function CourseCard({
  title,
  duration,
  isPublished
}: CourseCardProps) {
  return (
    <article>
      <h2>{title}</h2>
      <p>Duration: {duration} hours</p>
      <p>{isPublished ? "Published" : "Draft"}</p>
    </article>
  );
}

function App() {
  return (
    <CourseCard
      title="TypeScript Fundamentals"
      duration={12}
      isPublished={true}
    />
  );
}

export default App;

CourseCardProps declares the contract that CourseCard expects. The title property must be a string, duration must be a number, and isPublished must be a boolean.

If a developer supplies a string for duration or omits a required property, TypeScript reports a type error during development.

Props should generally be treated as read-only inputs. When a component needs to change a value, it should usually use its own state or notify its parent through a callback rather than modifying a prop directly.

3. Using Optional Props and Default Values

Some component properties are not required for every use case. TypeScript supports optional properties through the question mark syntax.

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>
  );
}

function App() {
  return (
    <div>
      <Button label="Save" />
      <Button
        label="Cancel"
        variant="secondary"
      />
      <Button
        label="Submitting..."
        disabled={true}
      />
    </div>
  );
}

The variant property accepts only the literal values primary or secondary. This is more restrictive than a general string and prevents unsupported variants from being passed accidentally.

The destructuring defaults provide values when optional properties are undefined. This keeps the component behavior predictable without requiring every parent to supply every prop.

Use optional props when a component genuinely supports multiple configurations. Avoid making every property optional simply to suppress compiler errors, because doing so weakens the component's contract.

4. Typing React State with useState

React's useState hook stores values that can change during a component's lifetime. TypeScript can infer many state types from their initial values, but explicit generic arguments are helpful when the initial value does not fully represent the possible state.

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <section>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </section>
  );
}

export default Counter;

The generic type number specifies that count is numeric. TypeScript can reject attempts to update it with an incompatible value.

For state initialized with null, provide a union when the value can later hold another type.

interface User {
  id: number;
  name: string;
}

const [user, setUser] = useState<User | null>(null);

// Later, after loading valid user data:
setUser({
  id: 101,
  name: "Abhinash"
});

// Reset the state:
setUser(null);

The User | null type explicitly represents the two supported states: a loaded user or no user. Before accessing user.name, check whether user is not null so TypeScript can narrow the value safely.

5. Typing React Event Handlers

React event handlers respond to actions such as clicks, text input, form submission, and keyboard interaction. TypeScript provides event types that describe the properties available for each event.

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

function EventExamples() {
  function handleClick(
    event: MouseEvent<HTMLButtonElement>
  ) {
    console.log(event.currentTarget.disabled);
  }

  function handleChange(
    event: ChangeEvent<HTMLInputElement>
  ) {
    console.log(event.currentTarget.value);
  }

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

  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />

      <button type="button" onClick={handleClick}>
        Check button
      </button>

      <button type="submit">Submit</button>
    </form>
  );
}

ChangeEvent for HTMLInputElement provides access to the input's value. FormEvent for HTMLFormElement is suitable for form submission, while MouseEvent for HTMLButtonElement describes a mouse event associated with a button.

React can infer event parameter types when handlers are declared directly in JSX. Explicit annotations are particularly useful when handlers are extracted into reusable functions or passed between components.

Select the event type and element type that match the actual control. A button event and a form event do not expose identical properties, so using an accurate type makes the available operations clearer.

6. Building Type-Safe Forms

Forms often contain multiple fields whose values must remain consistent with a shared model. Defining a form interface allows the component's state, change handlers, and submission logic to use the same contract.

import { useState } from "react";
import type {
  ChangeEvent,
  FormEvent
} from "react";

interface LoginForm {
  email: string;
  password: string;
}

function Login() {
  const [form, setForm] = useState<LoginForm>({
    email: "",
    password: ""
  });

  function handleChange(
    event: ChangeEvent<HTMLInputElement>
  ) {
    const { name, value } = event.currentTarget;

    if (name !== "email" && name !== "password") {
      return;
    }

    setForm(previous => ({
      ...previous,
      [name]: value
    }));
  }

  function handleSubmit(
    event: FormEvent<HTMLFormElement>
  ) {
    event.preventDefault();

    if (!form.email.trim() || !form.password) {
      return;
    }

    console.log("Login form is ready to submit.");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="email"
        type="email"
        value={form.email}
        onChange={handleChange}
        required
      />

      <input
        name="password"
        type="password"
        value={form.password}
        onChange={handleChange}
        required
      />

      <button type="submit">Log in</button>
    </form>
  );
}

LoginForm defines the expected form state, and useState keeps the object consistent with that interface. The change handler reads the input name and value, while the submission handler prevents the browser's default form submission.

The name check prevents arbitrary input names from being used to update this particular form model. For larger forms, a generic field update helper or a dedicated form library may provide a more maintainable solution.

This example demonstrates client-side form state and basic checks. A real login workflow should submit credentials through a secure authentication endpoint, handle unsuccessful responses, and avoid logging sensitive values.

7. Typing Children and ReactNode

Many components need to display content supplied by their parent. ReactNode is a useful type for children because it represents the kinds of values React can render, including elements, strings, numbers, and collections of renderable content.

import type { ReactNode } from "react";

interface CardProps {
  title: string;
  children: ReactNode;
}

function Card({ title, children }: CardProps) {
  return (
    <section className="card">
      <h2>{title}</h2>
      <div>{children}</div>
    </section>
  );
}

function App() {
  return (
    <Card title="Course details">
      <p>Learn TypeScript fundamentals.</p>
      <button>Start learning</button>
    </Card>
  );
}

The Card component accepts a title string and children typed as ReactNode. This makes the component reusable with different kinds of content without requiring a separate component for each layout.

ReactNode is broader than ReactElement. Use ReactNode when a prop should accept renderable content, and use a more specific type when the component genuinely requires a particular kind of element or value.

8. Typing Props with Discriminated Unions

Discriminated unions help define components with multiple supported modes. They are especially useful when different variants require different properties.

type AlertProps =
  | {
      variant: "success";
      message: string;
    }
  | {
      variant: "error";
      message: string;
      retry: () => void;
    };

function Alert(props: AlertProps) {
  if (props.variant === "success") {
    return <p role="status">{props.message}</p>;
  }

  return (
    <div role="alert">
      <p>{props.message}</p>
      <button onClick={props.retry}>Retry</button>
    </div>
  );
}

function App() {
  return (
    <div>
      <Alert
        variant="success"
        message="Changes saved."
      />

      <Alert
        variant="error"
        message="Unable to save."
        retry={() => console.log("Retrying")}
      />
    </div>
  );
}

The variant property distinguishes the two shapes of AlertProps. A success alert requires a message but does not require a retry callback. An error alert requires both.

Inside Alert, checking variant narrows the props to the appropriate union member. This lets TypeScript determine when retry is available.

Discriminated unions are useful for buttons, alerts, loading states, navigation items, and other components whose properties depend on a selected variant.

9. Creating Generic React Components

Generic components can render different data types while preserving the relationship between input data and callback parameters. They are useful for reusable lists, tables, selectors, and other data-driven interfaces.

interface Course {
  id: number;
  title: string;
}

interface GenericListProps {
  items: T[];
  getKey: (item: T) => string | number;
  renderItem: (item: T) => React.ReactNode;
}

function GenericList({
  items,
  getKey,
  renderItem
}: GenericListProps) {
  return (
    <ul>
      {items.map(item => (
        <li key={getKey(item)}>
          {renderItem(item)}
        </li>
      ))}
    </ul>
  );
}

const courses: Course[] = [
  { id: 1, title: "TypeScript Basics" },
  { id: 2, title: "Advanced TypeScript" }
];

function App() {
  return (
    <GenericList
      items={courses}
      getKey={course => course.id}
      renderItem={course => <span>{course.title}</span>}
    />
  );
}

The generic parameter T represents the item type. When items is Course[], TypeScript infers T as Course and supplies that type to getKey and renderItem.

This prevents callbacks from accidentally accessing properties that do not exist on the selected item type.

In this example, React.ReactNode is used as the renderItem return type. Projects that prefer named type imports can import ReactNode from React and use it directly.

Generic components are most valuable when the same behavior is genuinely useful across multiple data types. Avoid introducing generics into components that only ever handle one simple model.

10. Typing useRef and DOM Elements

The useRef hook stores a value that persists between renders. It is commonly used to access DOM elements or maintain mutable values that should not trigger a render when updated.

import { useRef } from "react";

function SearchInput() {
  const inputRef = useRef<HTMLInputElement | null>(null);

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

  return (
    <section>
      <input
        ref={inputRef}
        type="search"
        placeholder="Search courses"
      />

      <button onClick={focusInput}>
        Focus search
      </button>
    </section>
  );
}

The HTMLInputElement type describes the DOM element that the ref points to. The current property can be null when the element is not mounted.

Optional chaining prevents focusInput from calling focus when the reference is null. This avoids assuming that the DOM element always exists.

Choose the appropriate DOM type for the referenced element. For example, use HTMLButtonElement for a button and HTMLFormElement for a form. Accurate element types provide access to the correct DOM properties and methods.

11. Typing React Context

React Context allows values to be shared across a component tree without passing props through every intermediate component. TypeScript can define the shape of the shared value and help components consume it correctly.

import {
  createContext,
  useContext
} from "react";

interface AuthContextValue {
  userId: number | null;
  isAuthenticated: boolean;
}

const AuthContext =
  createContext<AuthContextValue | undefined>(undefined);

function useAuth(): AuthContextValue {
  const context = useContext(AuthContext);

  if (context === undefined) {
    throw new Error(
      "useAuth must be used inside AuthContext.Provider."
    );
  }

  return context;
}

function UserStatus() {
  const auth = useAuth();

  return (
    <p>
      {auth.isAuthenticated
        ? "Authenticated"
        : "Not authenticated"}
    </p>
  );
}

AuthContextValue defines the shared context structure. The context itself includes undefined to represent the absence of a provider value.

The useAuth hook checks whether the context exists before returning it. After the check, TypeScript knows the result is AuthContextValue.

This pattern produces a clearer error when a component is rendered outside the expected provider. It also prevents every consumer from repeatedly handling an undefined context value.

The example demonstrates typing only. A complete authentication provider must supply the context value and implement its authentication behavior, and the context itself is not a security boundary.

12. Typing API Data in React Components

React components frequently retrieve data from APIs. A response type can describe the expected data, while runtime validation helps ensure that the actual payload matches that type.

import { useEffect, useState } from "react";

interface Course {
  id: number;
  title: string;
}

function isCourseArray(value: unknown): value is Course[] {
  return (
    Array.isArray(value) &&
    value.every(
      item =>
        typeof item === "object" &&
        item !== null &&
        "id" in item &&
        typeof item.id === "number" &&
        "title" in item &&
        typeof item.title === "string"
    )
  );
}

function CourseList() {
  const [courses, setCourses] = useState<Course[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadCourses() {
      try {
        const response = await fetch("/api/courses");

        if (!response.ok) {
          throw new Error("Unable to load courses.");
        }

        const payload: unknown = await response.json();

        if (!isCourseArray(payload)) {
          throw new Error("Invalid course response.");
        }

        setCourses(payload);
      } catch {
        setError("Courses could not be loaded.");
      }
    }

    void loadCourses();
  }, []);

  if (error !== null) {
    return <p role="alert">{error}</p>;
  }

  return (
    <ul>
      {courses.map(course => (
        <li key={course.id}>{course.title}</li>
      ))}
    </ul>
  );
}

The courses state is typed as Course[], while the error state can contain either a string or null. This makes the possible state values explicit.

The API response is treated as unknown and validated before it is passed to setCourses. The type guard checks that the payload is an array and that every item contains the required id and title properties with the expected types.

The effect starts the asynchronous request when the component mounts. The void operator makes the intentional fire-and-forget invocation explicit, while the asynchronous function handles its own failures.

For production applications, also consider request cancellation or stale-response handling when components unmount or request parameters change. Larger applications may benefit from a data-fetching library that manages caching, retries, and request state.

13. Reusing Existing HTML Prop Types

React and TypeScript provide ways to derive prop types from existing components or HTML elements. This can reduce duplication when creating wrappers around standard controls.

import type { ComponentProps } from "react";

type NativeButtonProps = ComponentProps<"button">;

interface PrimaryButtonProps extends NativeButtonProps {
  label: string;
}

function PrimaryButton({
  label,
  type = "button",
  ...buttonProps
}: PrimaryButtonProps) {
  return (
    <button type={type} {...buttonProps}>
      {label}
    </button>
  );
}

function App() {
  return (
    <PrimaryButton
      label="Save changes"
      disabled={false}
      onClick={() => console.log("Saved")}
    />
  );
}

ComponentProps can derive the existing prop type for a native button. Extending that type allows PrimaryButton to accept standard button properties without manually redefining every HTML attribute and event handler.

The component adds a required label while retaining useful native properties such as disabled, onClick, and type.

This technique is helpful for design systems and reusable component libraries. When building wrappers, deliberately decide which native props should remain available and which should be restricted to preserve the component's intended behavior.

14. Common Mistakes in Type-Safe React

  • Using any for props or state: any disables many checks. Define a model that describes the actual data instead.
  • Treating API annotations as validation: assigning JSON to a typed variable does not confirm that the server returned the expected properties.
  • Incorrect event types: use the event type and DOM element type that match the control being handled.
  • Mutating state directly: create updated state values through React state setters rather than modifying existing objects or arrays in place.
  • Making every prop optional: optional properties should represent genuine flexibility, not conceal incomplete component usage.
  • Ignoring null state: explicitly represent missing values with null or undefined when appropriate and narrow them before accessing properties.
  • Overusing type assertions: assertions do not validate runtime values. Prefer narrowing and validation when the value is uncertain.
  • Creating unnecessarily complicated generics: introduce generic components when they provide real reuse and preserve meaningful type relationships.

15. Best Practices for Type-Safe React

  • Define clear interfaces or type aliases for component props and important state models.
  • Use TypeScript's inference when it accurately describes the intended type, and add explicit annotations when they improve clarity.
  • Use literal unions for finite component variants instead of accepting arbitrary strings.
  • Type extracted event handlers and DOM refs according to their actual elements.
  • Use ReactNode for renderable children and ComponentProps when deriving native element or existing component prop types.
  • Use generics for reusable components and hooks when they preserve meaningful relationships between inputs and outputs.
  • Represent loading, success, and error states with explicit types instead of unrelated boolean flags where a union is clearer.
  • Validate external API responses before passing them into typed state.
  • Keep reusable types near the functionality that owns them and share types when multiple components genuinely depend on the same contract.
  • Use runtime tests and validation alongside static typing because TypeScript cannot prevent every runtime failure.

Conclusion

Type-safe React development combines React's component model with TypeScript's static type system. Typed props establish component contracts, typed state makes changing values predictable, and accurate event and ref types improve interactions with the DOM.

Generics enable reusable components, discriminated unions represent variant-dependent props and submission states, and runtime validation protects components from malformed external data.

By choosing accurate types, avoiding unnecessary assertions, and validating values at runtime boundaries, you can build React applications that are easier to understand, test, and maintain.

Code Examples

Create a React Component with Typed Props

typescript
interface CourseCardProps {
  title: string;
  duration: number;
  isPublished: boolean;
}

function CourseCard({
  title,
  duration,
  isPublished
}: CourseCardProps) {
  return (
    <article>
      <h2>{title}</h2>
      <p>Duration: {duration} hours</p>
      <p>{isPublished ? "Published" : "Draft"}</p>
    </article>
  );
}

export default CourseCard;
    

Use Type-Safe React State

typescript
import { useState } from "react";

interface User {
  id: number;
  name: string;
}

function UserProfile() {
  const [user, setUser] = useState<User | null>(null);

  function loadUser() {
    setUser({
      id: 101,
      name: "Abhinash"
    });
  }

  return (
    <section>
      {user !== null ? <p>{user.name}</p> : <p>No user loaded.</p>}
      <button onClick={loadUser}>Load user</button>
    </section>
  );
}

export default UserProfile;
    

Type React Event Handlers

typescript
import type {
  ChangeEvent,
  FormEvent
} from "react";

function SearchForm() {
  function handleChange(
    event: ChangeEvent<HTMLInputElement>
  ) {
    console.log(event.currentTarget.value);
  }

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

  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />
      <button type="submit">Search</button>
    </form>
  );
}

export default SearchForm;
    

Build a Reusable Generic List

typescript
import type { ReactNode } from "react";

interface GenericListProps<T> {
  items: T[];
  getKey: (item: T) => string | number;
  renderItem: (item: T) => ReactNode;
}

function GenericList<T>({
  items,
  getKey,
  renderItem
}: GenericListProps<T>) {
  return (
    <ul>
      {items.map(item => (
        <li key={getKey(item)}>
          {renderItem(item)}
        </li>
      ))}
    </ul>
  );
}

interface Course {
  id: number;
  title: string;
}

const courses: Course[] = [
  { id: 1, title: "TypeScript Basics" },
  { id: 2, title: "Advanced TypeScript" }
];

function App() {
  return (
    <GenericList
      items={courses}
      getKey={course => course.id}
      renderItem={course => <span>{course.title}</span>}
    />
  );
}

export default App;
    

Use a Typed DOM Ref

typescript
import { useRef } from "react";

function SearchInput() {
  const inputRef = useRef<HTMLInputElement | null>(null);

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

  return (
    <section>
      <input ref={inputRef} placeholder="Search courses" />
      <button onClick={focusInput}>Focus search</button>
    </section>
  );
}

export default SearchInput;
    

Validate API Data Before Updating State

typescript
interface Course {
  id: number;
  title: string;
}

function isCourseArray(value: unknown): value is Course[] {
  return (
    Array.isArray(value) &&
    value.every(
      item =>
        typeof item === "object" &&
        item !== null &&
        "id" in item &&
        typeof item.id === "number" &&
        "title" in item &&
        typeof item.title === "string"
    )
  );
}

async function fetchCourses(): Promise<Course[]> {
  const response = await fetch("/api/courses");

  if (!response.ok) {
    throw new Error("Unable to load courses.");
  }

  const payload: unknown = await response.json();

  if (!isCourseArray(payload)) {
    throw new Error("Invalid course response.");
  }

  return payload;
}
    

Pro Tip

Define component props and state using the narrowest useful types. Use discriminated unions for component variants, generics for reusable components, and ComponentProps to reuse existing React prop definitions. Treat API responses as unknown until validated, because TypeScript annotations alone do not verify external data at runtime.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.