# React Hooks Typing

> Type-safe state management.

Subject: TypeScript | Lesson 52 of 54 | 5 min read
Interactive lesson: https://codewithanimation.in/typescript/react-hooks-typing
Previous: [React Component Typing](https://codewithanimation.in/typescript/react-component-typing.md) | Next: [React Event Handlers](https://codewithanimation.in/typescript/react-event-handlers.md)

## Typing State

For simple state, TypeScript infers the type automatically: `const [count, setCount] = useState(0)` infers `number`.

But for complex state, especially when using `useReducer`, you must explicitly define the shapes of all possible state transitions.

## The Optional Payload Trap

A common mistake when typing a reducer action is `type Action = { type: string, payload?: any }`.

This is dangerous! It allows you to dispatch `{ type: 'INCREMENT', payload: 'foo' }`, even though incrementing shouldn't take a payload, and certainly not a string.

The correct pattern is a **Discriminated Union**.

## Syntax

```tsx
// 1. Define exact action shapes
type Action = 
  | { type: "INCREMENT" }
  | { type: "DECREMENT" }
  | { type: "SET_VALUE"; payload: number };

// 2. Type the Reducer
function reducer(state: number, action: Action) {
  switch (action.type) {
    case "INCREMENT": return state + 1;
    case "SET_VALUE": return action.payload; // Type-safe!
  }
}
```

## Common mistake: useRef Nullability

When typing `useRef` for a DOM element, you must initialize it with `null`: `useRef<HTMLDivElement>(null)`. If you don't pass `null`, TypeScript assumes you want a mutable variable ref instead of a DOM ref, which leads to read-only errors.

## Tip: useState Generics

If your state starts as `null` but will eventually be a `User` object, you must provide a generic: `useState<User | null>(null)`.

## Try it: Try it

Select an action type to dispatch, and watch how the Discriminated Union instantly restricts whether a `payload` is allowed, required, or forbidden.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/react-hooks-typing

## Check yourself

### Question 1

Why is a Discriminated Union better than making `payload` optional for `useReducer` actions?

- A. It prevents the reducer from running twice in React Strict Mode.
- B. It explicitly links specific action types to specific payload shapes, preventing invalid combinations.
- C. It compiles down to faster JavaScript switch statements.

Correct answer: B

Discriminated unions provide strict, per-action type safety. If you use an optional payload, TypeScript cannot guarantee that a required payload was actually provided for a specific action.

## Remember this

- Simple `useState(0)` is auto-inferred.
- Complex `useState<User | null>(null)` requires a generic.
- Always type `useReducer` actions using a Discriminated Union.
- Always initialize DOM `useRef` with `null`.
