How to Use TypeScript with React: A Practical Tutorial

TypeScript brings static typing to React, catching bad props, missing state, and null errors before your code ever runs in a browser. If you already know React, adding types takes minutes and pays off immediately.

This tutorial covers the setup and the four patterns you will use in almost every component.

Article illustration

1. Create a Typed Project

Scaffold with a template that already wires up the compiler:

  • npm create vite@latest my-app -- --template react-ts
  • Or run npx create-next-app@latest --ts

Rename any existing files from .jsx to .tsx, and set "strict": true in tsconfig.json to get full type checking.

2. Type Your Props

Give every component an interface describing what it accepts:

interface ButtonProps { label: string; onClick: () => void; disabled?: boolean; }

The ? marks a prop as optional. For wrapper components, add children: React.ReactNode. TypeScript now flags any missing or mistyped prop at the call site.

3. Type Hooks and Events

  • useState<string>("") — set the state type explicitly when inference is not enough.
  • useRef<HTMLInputElement>(null) — get typed access to DOM nodes.
  • (e: React.ChangeEvent<HTMLInputElement>) => ... — type event handlers accurately.

Conclusion

Start with typed props and state, then move on to generics and utility types like Partial and Pick. Your editor’s autocomplete will guide the rest.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *