React is one of the most popular JavaScript libraries for building user interfaces. But when you combine it with TypeScript, you get type safety, better tooling, and fewer runtime errors. 🚀
If you’re just starting with React + TypeScript, this guide will help you set up your project and understand the basics.
🛠 1. Create a New React + TypeScript Project
The easiest way is with Vite (fast and lightweight):
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev
👉 This sets up a React + TypeScript project instantly.
📦 2. Type Your Props
In plain React, you might write:
function Greeting(props) {
return
Hello, {props.name}!
;}
With TypeScript, we define the prop type:
type GreetingProps = {
name: string;
age?: number; // optional
};
function Greeting({ name, age }: GreetingProps) {
return (
Hello, {name}! {age && (Age: ${age})
}
);
}
export default Greeting;
✅ Benefits:
Autocomplete in your IDE
Type checking at compile time
No more “undefined” surprises
🔄 3. Using useState with Types
Sometimes TypeScript can’t infer the state type. You can explicitly type it:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
setCount(count + 1)}>➕ Increment
);
}
export default Counter;
Here, useState(0) ensures count will always be a number.
🌍 4. Typing API Responses
When fetching data, you can define an interface:
type User = {
id: number;
name: string;
email: string;
};
async function fetchUsers(): Promise {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
}
Now whenever you use User, you’ll get intellisense + safety.
🎯 Final Thoughts
React + TypeScript might feel like extra work at first, but the confidence and productivity you gain are worth it.
Your IDE will catch bugs before they occur at runtime.
Your codebase will be easier to maintain.
Your teammates will thank you. 🙌
👉 Are you using TypeScript with React in your projects? Share your experience below!
Top comments (0)