TypeScript Tips for React Developers
TypeScript and React make a powerful combination, but getting the most out of them requires understanding some key patterns and best practices.
Component Props with Generics
Create flexible, reusable components with generic props:
```typescript interface ListProps<T> { items: T[]; renderItem: (item: T) => React.ReactNode; }
function List<T>({ items, renderItem }: ListProps<T>) { return ( <ul> {items.map((item, index) => ( <li key={index}>{renderItem(item)}</li> ))} </ul> ); } ```
Discriminated Unions for State
Use discriminated unions to model complex state:
```typescript type AsyncState<T> = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; error: string };
function useAsyncData<T>() { const [state, setState] = useState<AsyncState<T>>({ status: 'idle' }); // Implementation... } ```
Custom Hook Types
Type your custom hooks properly:
```typescript function useLocalStorage<T>( key: string, initialValue: T ): [T, (value: T | ((val: T) => T)) => void] { // Implementation... } ```
Conclusion
TypeScript makes React development more predictable and maintainable. These patterns will help you write better, more type-safe React applications.