How to use TypeScript with React
· Category: TypeScript
Short answer
TypeScript integrates with React through type definitions for JSX, component props, state, and hooks, providing compile-time checks for your UI layer.
Steps
- Create a functional component with typed props:
interface ButtonProps { label: string; onClick: () => void; }
const Button: React.FC<ButtonProps> = ({ label, onClick }) => ...
- Type useState:
const [count, setCount] = useState<number>(0); - Type event handlers:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => ... - Type refs with
useRef<HTMLInputElement>(null). - Use generic components for reusable lists and tables.
Tips
- Use
React.ComponentPropsto extract prop types from HTML elements or third-party components. - Prefer explicit return types on public components for clearer error messages.
Common issues
- Children prop typing can be tricky; use
React.ReactNodefor maximum flexibility. - Event types vary by element; using the wrong one causes subtle type mismatches.