TypeScript with React
⚛️ TypeScript with React
🧠 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)
This creates a ready-made React + TypeScript setup.
Option B: Using Vite (Recommended ⭐)
Vite is faster and lighter than CRA.
📁 Typical Project Structure
📌 .tsx → TypeScript + JSX
🧩 2️⃣ Functional Component in TypeScript
Type inference works automatically 👍
🧾 3️⃣ Props with TypeScript
Define Props Type
Use Props
🧠 4️⃣ State with TypeScript (useState)
📌 TypeScript infers count as number.
🎯 5️⃣ Event Handling
📦 6️⃣ Typing Forms
🧠 7️⃣ useEffect with Types
(No extra types needed most of the time)
🧱 8️⃣ Typing Children
🧩 9️⃣ Refs with TypeScript
🧪 🔟 API Data Typing
🔑 Common React + TypeScript Types
| Use Case | Type |
|---|---|
| Props | type Props = {} |
| State | useState<Type>() |
| Events | React.MouseEvent |
| Forms | React.ChangeEvent |
| Children | React.ReactNode |
| Refs | useRef<Type> |
⭐ Best Practices
✔ Prefer function components
✔ Use type for props
✔ Avoid any
✔ Keep shared types in /types folder
✔ Let TypeScript infer when possible
📌 Summary
.tsxfiles are used for React + TSProps & state are fully type-safe
Better DX and fewer runtime bugs
Ideal for scalable React apps
