React with TypeScript — Best Practices
Advertisement
React with TypeScript — Best Practices
TypeScript with React provides type safety and excellent developer experience.
- React with TypeScript — Best Practices
- Function Components
- Event Handlers
- Children Props
- Generic Components
- Hooks with TypeScript
- FAQ
Function Components
interface UserProps {
id: string
name: string
isActive?: boolean
}
export function User({ id, name, isActive = true }: UserProps) {
return <div>{name}</div>
}
Event Handlers
function Form() {
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value)
}
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
}
return (
<form>
<input onChange={handleChange} />
<button onClick={handleClick}>Submit</button>
</form>
)
}
Children Props
interface LayoutProps {
children: React.ReactNode
}
function Layout({ children }: LayoutProps) {
return <div>{children}</div>
}
Generic Components
interface ListProps<T> {
items: T[]
renderItem: (item: T) => React.ReactNode
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map(renderItem)}</ul>
}
Hooks with TypeScript
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
return initialValue
}
})
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (error) {
console.log(error)
}
}
return [storedValue, setValue] as const
}
FAQ
Q: Should I type children? A: Always use React.ReactNode for children prop.
Q: How do I type refs? A: useRef<HTMLInputElement>(null)
Q: What about unknown vs any? A: Use unknown, then narrow types. Avoid any.
TypeScript in React catches errors early and improves code quality.
Advertisement