TypeScript with React

⚛️ TypeScript with React

Using TypeScript with React gives you type-safe components, fewer bugs, and a much better developer experience—especially in medium to large React apps.

🧠 Why Use TypeScript with React?

✅ Type-safe props & state
✅ Better auto-complete in JSX
✅ Early error detection
✅ Easier refactoring
✅ More maintainable code


🚀 1️⃣ Create a React + TypeScript App

Option A: Using Create React App (Beginner Friendly)

npx create-react-app my-app --template typescript
cd my-app
npm start

This creates a ready-made React + TypeScript setup.


Option B: Using Vite (Recommended ⭐)

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

Vite is faster and lighter than CRA.


📁 Typical Project Structure

src/

├── App.tsx
├── main.tsx
├── components/
│ └── Header.tsx
├── types/
│ └── user.ts
└── index.css

📌 .tsx → TypeScript + JSX


🧩 2️⃣ Functional Component in TypeScript

function App() {
return <h1>Hello React + TypeScript</h1>;
}
export default App;

Type inference works automatically 👍


🧾 3️⃣ Props with TypeScript

Define Props Type

type GreetingProps = {
name: string;
age?: number;
};

Use Props

function Greeting({ name, age }: GreetingProps) {
return (
<p>
Hello {name} {age && `(${age})`}
</p>
);
}

🧠 4️⃣ State with TypeScript (useState)

import { useState } from "react";

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

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

📌 TypeScript infers count as number.


🎯 5️⃣ Event Handling

function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
console.log("Clicked");
}
<button onClick={handleClick}>Click</button>


📦 6️⃣ Typing Forms

function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
console.log(e.target.value);
}
<input type=“text” onChange={handleChange} />


🧠 7️⃣ useEffect with Types

import { useEffect } from "react";

useEffect(() => {
console.log(“Component mounted”);
}, []);

(No extra types needed most of the time)


🧱 8️⃣ Typing Children

type BoxProps = {
children: React.ReactNode;
};
function Box({ children }: BoxProps) {
return <div>{children}</div>;
}


🧩 9️⃣ Refs with TypeScript

import { useRef } from "react";

const inputRef = useRef<HTMLInputElement>(null);

<input ref={inputRef} />


🧪 🔟 API Data Typing

type User = {
id: number;
name: string;
};
const users: User[] = await fetch(“/api/users”).then(res => res.json());


🔑 Common React + TypeScript Types

Use CaseType
Propstype Props = {}
StateuseState<Type>()
EventsReact.MouseEvent
FormsReact.ChangeEvent
ChildrenReact.ReactNode
RefsuseRef<Type>

⭐ Best Practices

✔ Prefer function components
✔ Use type for props
✔ Avoid any
✔ Keep shared types in /types folder
✔ Let TypeScript infer when possible


📌 Summary

  • .tsx files are used for React + TS

  • Props & state are fully type-safe

  • Better DX and fewer runtime bugs

  • Ideal for scalable React apps

You may also like...