Free 20-minute strategy call with a senior engineer: AI, payments, eLearning or custom software
Engineering

How to Use TypeScript with React: Step-by-Step Guide

How to Use TypeScript with React: Building a Strong Foundation

In short

How to use TypeScript with React: set up with Vite or Next.js, then type props, state, events, refs, hooks, context and API data, with best practices.

TypeScript has become the standard way to build robust, scalable React applications. By adding static types to JavaScript, it catches mistakes before they reach users, makes components easier to understand and gives you far better autocompletion and refactoring. This guide shows how to use TypeScript with React step by step: setting up a project, typing props, state, events, hooks and API data, and the best practices that keep large codebases healthy.

Quick answer: create a new project with Vite (npm create vite@latest my-app -- --template react-ts) or Next.js (npx create-next-app@latest, which uses TypeScript by default). Write components in .tsx files, describe props with a type or interface, let TypeScript infer state where it can, add explicit generics for useState, useRef and context when needed, type API responses, and turn on strict mode in tsconfig.json.

What is TypeScript?

TypeScript is a superset of JavaScript that adds optional static typing. You describe the shape of your data, and the TypeScript compiler checks your code before it runs. TypeScript compiles to plain JavaScript, so it works anywhere JavaScript does.

JavaScript:

let name = "Alice";
name = 30; // allowed, but probably a bug

TypeScript:

let name: string = "Alice";
name = 30; // error: Type 'number' is not assignable to type 'string'

React with JavaScript or TypeScript?

React works perfectly with plain JavaScript, but TypeScript adds a safety net that becomes more valuable as the application grows.

JavaScriptTypeScript
Error detectionAt runtime, often by usersWhile you type and at build time
Props documentationComments or PropTypesTypes checked by the compiler
RefactoringRisky in large codebasesSafe, with editor support
AutocompletionLimitedRich and accurate
Learning curveLowerSlightly higher at first
Best forSmall projects and prototypesMost professional and long-lived apps

Drawbacks to be aware of: a learning curve for developers new to static typing, some extra code for complex types, and occasional friction with untyped third-party libraries.

Why use TypeScript with React?

  • Prop safety: components can only be used with the props they expect.
  • Safer state and data: state, context and API responses have known shapes.
  • Better refactoring: rename a prop or field and the compiler shows every place to update.
  • Easier collaboration: types act as always-up-to-date documentation.
  • Fewer runtime errors: many bugs are caught before code is merged.

1. Set up a React project with TypeScript

New project with Vite (recommended for single-page apps):

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

New project with Next.js (recommended for full-stack and SEO-friendly sites):

npx create-next-app@latest my-app

Create React App is no longer recommended for new projects; use Vite, Next.js or another modern framework instead.

Adding TypeScript to an existing React project:

npm install --save-dev typescript @types/react @types/react-dom
npx tsc --init

Then rename files from .jsx to .tsx gradually, starting with shared components and utilities.

Free resource

Upgrade and patching checklist

Want this applied to your project? Our engineers will send it with notes for your stack.

Get it free

2. Project structure and file extensions

  • .tsx for files that contain JSX (components).
  • .ts for plain TypeScript (utilities, API clients, types).

A common structure:

src/
  components/
    Greeter.tsx
  hooks/
    useUsers.ts
  types/
    user.ts
  api/
    client.ts
  App.tsx
  main.tsx

3. Typing component props

// src/components/Greeter.tsx
type GreeterProps = {
  name: string;
  greeting?: string; // optional prop
};

export function Greeter({ name, greeting = "Hello" }: GreeterProps) {
  return <h1>{greeting}, {name}!</h1>;
}

Typing the props parameter directly, as above, is the most common modern style. React.FC<Props> also works, but it is no longer necessary.

Children:

type CardProps = {
  title: string;
  children: React.ReactNode;
};

4. Interfaces and type aliases

Use them to describe your data once and reuse it everywhere:

// src/types/user.ts
export interface User {
  id: number;
  name: string;
  email: string;
  role: "admin" | "editor" | "viewer";
}

export type Product = {
  id: string;
  name: string;
  price: number;
};

Both work well; many teams use type for props and unions, and interface for object shapes that may be extended.

5. Typing state with useState

TypeScript infers simple state types:

const [count, setCount] = useState(0); // inferred as number

Add a generic when the initial value does not show the full type:

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

6. Typing events and refs

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

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    console.log(event.target.value);
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    inputRef.current?.focus();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input ref={inputRef} onChange={handleChange} />
    </form>
  );
}

7. Typing custom hooks and API data

// src/hooks/useUsers.ts
import { useEffect, useState } from "react";
import type { User } from "../types/user";

export function useUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/users")
      .then((res) => res.json() as Promise<User[]>)
      .then(setUsers)
      .catch(() => setError("Could not load users"));
  }, []);

  return { users, error };
}

TypeScript types disappear at runtime, so validate data from external APIs with a schema library such as Zod or Valibot when correctness matters. Libraries such as TanStack Query, React Hook Form and Redux Toolkit ship with their own TypeScript types.

8. Typing context

type AuthContextValue = {
  user: User | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
};

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

export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) throw new Error("useAuth must be used inside AuthProvider");
  return context;
}

9. Class components (legacy code)

New code should use function components and hooks. If you maintain older class components, pass the props and state types as generics:

type CounterState = { count: number };

class Counter extends React.Component<{}, CounterState> {
  state: CounterState = { count: 0 };

  render() {
    return <p>{this.state.count}</p>;
  }
}

10. Best practices for TypeScript with React

  • Enable strict mode in tsconfig.json to get the full benefit.
  • Avoid any; use unknown and narrow it, or write a proper type.
  • Keep shared types in one place (for example src/types) and generate API types from OpenAPI or GraphQL schemas where possible.
  • Validate external data at runtime with Zod or similar.
  • Run type checks in CI (tsc --noEmit) alongside ESLint with typescript-eslint.
  • Migrate gradually in existing projects, starting with the most reused code.

Frequently asked questions

How do I create a React app with TypeScript? Use Vite with the react-ts template or create a Next.js app, which uses TypeScript by default.

Should I use React.FC? It is optional. Most teams now type the props parameter directly, which is simpler and handles children explicitly.

Is TypeScript worth it for small React projects? For quick prototypes, plain JavaScript is fine. For anything you will maintain or grow, TypeScript usually pays for itself quickly.

Can I convert an existing React app to TypeScript gradually? Yes. Install TypeScript and the React type packages, then rename files to .tsx one at a time.

Read more: 10 compelling reasons to use TypeScript with React.

Build robust React applications with Vibidsoft

Vibidsoft Pvt Ltd builds type-safe React and Next.js applications and helps teams migrate existing JavaScript codebases to TypeScript. See our React development services or contact us for a free consultation.

Vibidsoft Engineering Team

Senior engineers who have shipped 450+ projects since 2014 across AI, payments, eCommerce, eLearning and custom software. Every guide is written and reviewed by the people who do the work.

Follow us on LinkedIn · About Vibidsoft

Next step

Talk to an engineer about Modernize & Rescue

Fixed-price upgrades for ageing PHP, Drupal, Magento or hybrid apps, with security patching and a care plan. from $5,000.

  • A 20-minute call with a senior engineer, not a salesperson
  • A written next-step plan within one business day
  • NDA on request
Book a call WhatsApp