React — TypeScript
Setup
npx create-react-app my-app --template typescript
Basic Component
interface Props {
name: string;
age: number;
}
function User({ name, age }: Props) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
State with TypeScript
function Counter() {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
);
}
TypeScript Examples
// Event handling
function Form() {
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
return (
<form onSubmit={handleSubmit}>
<input onChange={handleChange} />
</form>
);
}
// Generic component
function List<T>({ items, renderItem }: { items: T[]; renderItem: (item: T) => React.ReactNode }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);
}
// Usage
<List
items={['a', 'b', 'c']}
renderItem={(item) => <span>{item}</span>}
/>
TypeScript Examples
// API types
interface User {
id: number;
name: string;
email: string;
}
function useUsers() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
fetch('/api/users')
.then(res => res.json())
.then((data: User[]) => {
setUsers(data);
setLoading(false);
});
}, []);
return { users, loading };
}
// Context with TypeScript
interface ThemeContextType {
theme: string;
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
}
Mini Practice
Write React code that:
- Creates a typed component
- Uses state with TypeScript
- Handles events with TypeScript
- Creates a generic component
Up Next
Next: Learn about Next.js.
Related Topics
Frequently Asked Questions about TypeScript
What is TypeScript in React?
TypeScript is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn TypeScript?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn TypeScript.
Why is TypeScript important in React?
TypeScript is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.