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

Typing common hooks in TypeScript.

Generic useState type

Annotate nullable or union state explicitly.

tsxANYreacthookstypescriptuseState
tsx
const [user, setUser] = useState<User | null>(null);
Notes

Useful when TypeScript cannot infer the full intended state type from the initializer.

Type a DOM ref

Specify the element type for refs.

tsxANYreacthookstypescriptuseRef
tsx
const inputRef = useRef<HTMLInputElement | null>(null);
Notes

Typing refs correctly improves DOM API autocomplete and safety.

Discriminated union reducer actions

Type reducer actions cleanly with a union.

tsxANYreacthookstypescriptuseReducer
tsx
type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number };
Notes

Discriminated unions give exhaustive reducer switch safety.

TypeScript Custom Hooks

Typed custom hook APIs and generics.

Typed tuple return

Return readonly tuples for hooks that act like useState.

tsxANYreacthookstypescriptcustom-hooks
tsx
function useBoolean(initial = false): readonly [boolean, () => void] {
  const [value, setValue] = useState(initial);
  const toggle = () => setValue(v => !v);
  return [value, toggle] as const;
}
Notes

`as const` preserves tuple semantics for callers.

Generic async hook result type

Type reusable async hook data generically.

tsxANYreacthookstypescriptasync
tsx
type AsyncResult<T> = {
  data: T | null;
  error: Error | null;
  loading: boolean;
};
Notes

A reusable result type keeps async hook contracts consistent.

Recommended next

No recommendations yet.