# React + TypeScript Cheat Sheet for Beginners
---
## 1. Basic Component Props
### Function Component with Props
type Props = {
name: string;
age?: number; // optional prop
};
const Welcome = ({ name, age }: Props) => (
<h1>Hello, {name}! {age && `You are ${age}`}</h1>
);
---
## 2. State with useState
### Primitive
const [count, setCount] = useState<number>(0);
### Object
type User = {
name: string;
loggedIn: boolean;
};
const [user, setUser] = useState<User>({ name: '', loggedIn: false });
---
## 3. useEffect with Typed Functions
useEffect(() => {
console.log("Component mounted");
}, []);
---
## 4. Event Handlers
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
console.log("Clicked!");
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
---
## 5. Reusable Components with Children
type CardProps = {
children: React.ReactNode;
};
const Card = ({ children }: CardProps) => (
<div className="card">{children}</div>
);
---
## 6. Common Types
| Purpose | Type |
|-----------------------|-------------------------------------|
| HTML Element event | React.MouseEvent, React.ChangeEvent |
| Component props | type or interface |
| Component children | React.ReactNode |
| Function returning nothing | () => void |
| useRef with DOM node | useRef<HTMLDivElement>(null) |
---
## 7. File Extensions
| File Type | Extension |
|---------------------|-----------|
| React Component | .tsx |
| Logic-only TypeScript | .ts |
| Type definitions | types.ts or interfaces.ts |
---
## 8. Optional Tips
- Enable strict mode in tsconfig.json for full type safety
- Use `as` sparingly (type assertions should be a last resort)
- Use ESLint + Prettier for formatting and linting
---
## Example Component (All-in-One)
import { useState } from 'react';
type CounterProps = {
start: number;
};
const Counter = ({ start }: CounterProps) => {
const [count, setCount] = useState<number>(start);
const increment = () => setCount(count + 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default Counter;