TypeScript with React
Props interfaces, useState<T>, useRef<T>, event types, and React.FC
Skills taught: ts.react-props, ts.useState-generic, ts.useRef-generic, ts.react-events, ts.react-fc
Typed props and state
import React, { useState } from 'react';
// Props interface — required and optional props
interface ButtonProps {
label: string; // required
variant?: 'primary' | 'secondary' | 'danger'; // optional union type
disabled?: boolean;
onClick?: () => void;
}
// Function component with typed props
function Button({ label, variant = 'primary', disabled = false, onClick }: ButtonProps) {
return (
<button
disabled={disabled}
onClick={onClick}
className={`btn btn-${variant}`}
>
{label}
</button>
);
}
// Using Button — TypeScript checks props at call site:
// <Button /> ← Error: 'label' is required
// <Button label="Save" variant="invalid" /> ← Error: not in union
// <Button label="Save" /> ← OK
// <Button label="Delete" variant="danger" onClick={() => {}} /> ← OK
import React, { useState, useRef } from 'react';
// useState with explicit type
function Counter() {
const [count, setCount] = useState<number>(0);
const [name, setName] = useState<string>('');
// Typed event handlers
const handleInput = (e: React.ChangeEvent<HTMLInputElement>): void => {
setName(e.target.value);
};
return (
<div>
<input value={name} onChange={handleInput} placeholder="Name" />
<p>{name || 'Stranger'} clicked {count} times</p>
<button onClick={() => setCount(c => c + 1)}>+1</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
// useRef — typed element reference
function FocusInput() {
const inputRef = useRef<HTMLInputElement>(null);
const focusIt = (): void => {
// inputRef.current is HTMLInputElement | null
inputRef.current?.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={focusIt}>Focus</button>
</>
);
}
import React from 'react';
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user';
}
// Generic component — works with any item that has an id
interface ListProps<T extends { id: number }> {
items: T[];
renderItem: (item: T) => React.ReactNode;
emptyMessage?: string;
}
function List<T extends { id: number }>({ items, renderItem, emptyMessage = 'No items' }: ListProps<T>) {
if (items.length === 0) return <p>{emptyMessage}</p>;
return <ul>{items.map(item => <li key={item.id}>{renderItem(item)}</li>)}</ul>;
}
// Usage — TypeScript infers T as User from items prop:
const users: User[] = [
{ id: 1, name: 'Alice', email: 'a@ex.com', role: 'admin' },
{ id: 2, name: 'Bob', email: 'b@ex.com', role: 'user' },
];
function UserList() {
return (
<List
items={users}
renderItem={u => <span>{u.name} ({u.role})</span>}
emptyMessage="No users found"
/>
);
}
export { Button, Counter, FocusInput, UserList };
Frequently Asked Questions
Should I use React.FC or plain function components?
Modern React (18+) best practice: use plain function components with an explicit props interface. React.FC<Props> is fine but has some quirks (it used to include children implicitly, which is not always wanted). Plain function syntax is more explicit: function Button({ label }: ButtonProps): JSX.Element { ... } — the props and return type are clear. Most modern React codebases avoid React.FC.