React Hooks with TypeScript

Type-safe React Hooks patterns for state, refs, reducers, and custom hooks.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## TypeScript with State and Refs
Generic useState type
const [user, setUser] = useState<User | null>(null);

# Annotate nullable or union state explicitly.

Type a DOM ref
const inputRef = useRef<HTMLInputElement | null>(null);

# Specify the element type for refs.

Discriminated union reducer actions
type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number };

# Type reducer actions cleanly with a union.

## TypeScript Custom Hooks
Typed tuple return
function useBoolean(initial = false): readonly [boolean, () => void] {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(v => !v);
  return [value, toggle] as const;
}

# Return readonly tuples for hooks that act like useState.

Generic async hook result type
type AsyncResult<T> = {
  data: T | null;
  error: Error | null;
  loading: boolean;
};

# Type reusable async hook data generically.

Recommended next

No recommendations yet.