Foundations: TypeScript & Generics for Modern React
TypeScript & Generics: Type components, props, hooks, and complex data flows safely.
TypeScript in modern React is far more than sprinkling : string or : number across files. It acts as an active compile-time design partner that prevents subtle runtime crashes, guarantees that component contracts are respected, and ensures state transitions stay predictable across complex application workflows.
## 1. Typing Component Props & Children
Modern React favors standard functional component signatures over legacy helpers like React.FC or React.FunctionComponent.
### Why Ditch React.FC?
- **Implicit children:** Historically injected an optional children prop into every component, accepting nested JSX even when the component had nowhere to render it.
- **Awkward generics:** Made writing generic components (<T>) significantly more cumbersome.
- **Unnecessary abstraction:** Added wrapper ceremony without offering meaningful runtime or compile-time advantages.
### Idiomatic Prop Typing
Type props using plain TypeScript interface or type aliases, destructuring them directly in the parameter list:
```ts
import type { ReactNode, ComponentPropsWithoutRef } from 'react';
interface UserCardProps {
id: string;
name: string;
role?: 'admin' | 'editor' | 'viewer'; // Discriminated union of string literals
children?: ReactNode; // Idiomatic type for renderable content
onSelect: (id: string) => void; // Strongly typed event callback
}
export function UserCard({
id,
name,
role = 'viewer',
children,
onSelect,
}: UserCardProps) {
return (
(null);
useReducer: Discriminated Union Actions
```
Pairing useReducer with discriminated unions enforces exhaustive state-machine guarantees:
```ts
interface State {
count: number;
error: string | null;
}
// Discriminated union: 'type' acts as the discriminant tag
type Action =
| { type: 'INCREMENT'; step?: number }
| { type: 'DECREMENT'; step?: number }
| { type: 'RESET' }
| { type: 'SET_ERROR'; payload: string };
function counterReducer(state: State, action: Action): State {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + (action.step ?? 1), error: null };
case 'DECREMENT':
return { ...state, count: state.count - (action.step ?? 1), error: null };
case 'RESET':
return { count: 0, error: null };
case 'SET_ERROR':
// TypeScript guarantees action.payload exists ONLY on 'SET_ERROR'
return { ...state, error: action.payload };
default: {
// Exhaustiveness checking: triggers a compile-time error if a variant is unhandled
const _unhandled: never = action;
return state;
}
}
}
useRef: DOM Elements vs. Mutable Values
```
Typing useRef depends on whether it targets a native DOM node or holds an arbitrary mutable value:
```ts
import { useRef, useEffect } from 'react';
export function InputWithFocus() {
// 1. DOM Ref: Pass initial value `null` and target DOM type
// Typed as: RefObject (read-only .current)
const inputRef = useRef(null);
// 2. Mutable Value Ref: Pass initial value or explicit union
// Typed as: MutableRefObject
const timerRef = useRef(undefined);
useEffect(() => {
// TypeScript forces null-safety checks before accessing DOM APIs
inputRef.current?.focus();
timerRef.current = window.setTimeout(() => {
console.log('Timer fired');
}, 1000);
return () => clearTimeout(timerRef.current);
}, []);
return ;
}
```
## 3. Generic Components: Building Reusable Design Systems
Generics allow design system components to operate across diverse data models while preserving full type inference for consumers.
### Generic List / Table Pattern
```ts
import type { ReactNode } from 'react';
// Constrain T to objects that supply a unique identifier
interface ListProps {
items: T[];
renderItem: (item: T) => ReactNode;
onSelect?: (item: T) => void;
emptyFallback?: ReactNode;
}
// Declare the generic parameter on the function declaration
export function List({
items,
renderItem,
onSelect,
emptyFallback = ) {
if (items.length === 0) return <>{emptyFallback}>;
return (
onSelect(id)}>
);
}
```
### ReactNode vs. ReactElement vs. JSX.Element
- **ReactNode:** The broadest renderable type. Covers JSX elements, strings, numbers, fragments, booleans, null, and undefined. It is the idiomatic choice for children and slots.
- **ReactElement:** Represents an actual instantiated JSX element object (e.g., <Button/>). Excludes raw text, numbers, or null. Useful when a prop strictly demands another React element (e.g., icon: ReactElement).
- **JSX.Element:** Historically the return type of a JSX expression (internally extending ReactElement). In modern React with @types/react v18/v19, ReactNode is generally preferred for return type annotations.
### Polymorphic Components with Native Element Props
To allow custom primitives to accept all valid HTML attributes (such as aria-*, disabled, and tabIndex), extend ComponentPropsWithoutRef<T>:
```ts
import type { ComponentPropsWithoutRef } from 'react';
interface ButtonProps extends ComponentPropsWithoutRef<'button'> {
variant?: 'primary' | 'secondary' | 'danger';
isLoading?: boolean;
}
export function Button({
variant = 'primary',
isLoading = false,
children,
disabled,
...nativeProps
}: ButtonProps) {
return (
);
}
```
## 2. Typing React Hooks Safely
TypeScript excels at local type inference, but initial values often require explicit generic declarations.
useState
When initial state matches the exact type across the component's lifecycle, let TypeScript infer it:
```ts
const [count, setCount] = useState(0); // Inferred as number
const [text, setText] = useState(''); // Inferred as string
```
When state begins as null or undefined prior to an API fetch, pass an explicit union:
```ts
interface UserSession {
token: string;
expiresAt: number;
}
// Inferred as UserSession | null
const [session, setSession] = useState{name} ({role})
{children}No items found.
, }: ListProps-
{items.map((item) => (
- onSelect?.(item)}> {renderItem(item)} ))}
- (
{article.title} — {article.readTimeMinutes} min
)}
onSelect={(selected) => {
// 'selected' is strictly typed as Article
console.log(selected.title);
}}
```
/>
## 4. Generic Custom Hooks
Generic custom hooks eliminate duplicate logic while preserving precise return types for any calling component.
### Reusable Storage Hook
```ts
import { useState, useEffect } from 'react';
export function useLocalStorage
