Typing React Hooks, Generics, and Refs
Typing React Hooks, Generics, and Refs
While TypeScript's type inference handles simple hooks like useState(0) automatically, enterprise applications frequently require explicit generic typing for union states, null initializations, DOM references, and generic reusable custom hooks.
1. Typing useState
Inferred Primitives
Explicit Generics for Complex Types and Nullable State
When a state object starts as null before network data loads, type inference as null will error when assigning an object later. Provide an explicit generic union:
2. Typing useRef
useRef has two distinct use cases in TypeScript with very different type signatures:
Case A: DOM Element Reference (Read-Only Ref)
When referencing a physical DOM element, pass the HTML element type and initialize with null:
Case B: Mutable Mutable Variable (Value Container)
When using useRef as an instance variable that persists across renders without triggering re-renders (like a timer ID or WebSocket handle), provide the type without null initialization if not needed:
3. Typing useReducer
Discriminated unions provide complete type safety for reducer actions:
4. Generic Custom Hooks
Generic custom hooks allow components to consume typed utilities dynamically:
Practice Quiz
Typing Synthetic Events and Form Elements
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Typing Functional Components and Props in TypeScript | Typing Synthetic Events and Form Elements |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.