Why TypeScript with React?
TypeScript catches bugs at compile time and makes refactoring safe. Combined with React 18, you get a powerful stack for production apps.
Typed Component Props
hljs tsx
interface ButtonProps {
label: string;
onClick: () => void;
variant?: 'primary' | 'secondary';
}
function
Button({ label, onClick, variant = 'primary' }: ButtonProps) {
return <button onClick={onClick} className={variant}>{label}</button>;
}
Custom
Hooks
hljs tsx
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
const setStored = (newValue: T) => {
setValue(newValue);
localStorage.setItem(key,
JSON.stringify(newValue));
};
return [value, setStored] as const;
}
Performance with useMemo
hljs tsx
const expensiveResult = useMemo(() => {
return
heavyComputation(data);
}, [data]);
This prevents unnecessary recalculations on every render.
