Lesson 3 of 8
Typed Hooks - useState, useReducer, useRef
React hooks are generic. `useState<T>` types the state value. `useRef<T>` types the DOM element or imperative value. `useReducer<Reducer<S, A>>` types state and actions. TypeScript infers most of these from initial values - but knowing when to annotate explicitly is the key skill.
Typed Hooks - useState, useRef, useReducer
// ── useState - inference works from initial value ─────────────
const [count, setCount] = React.useState(0); // number
const [name, setName] = React.useState(""); // string
const [active, setActive] = React.useState(false); // boolean
// When initial value is null/undefined - explicit type required:
const [task, setTask] = React.useState<Task | null>(null);
const [tasks, setTasks] = React.useState<Task[]>([]); // empty array needs annotation
// ── useRef - DOM element refs ─────────────────────────────────
function TaskInput(): React.ReactElement {
const inputRef = React.useRef<HTMLInputElement>(null);
// Type: React.RefObject<HTMLInputElement>
// initial value is null (DOM not yet mounted)
const focus = (): void => {
inputRef.current?.focus(); // optional chaining - might be null
};
return <input ref={inputRef} onBlur={focus} />;
}
// useRef for mutable values (not DOM) - use non-null initial:
function Timer(): React.ReactElement {
const timerRef = React.useRef<ReturnType<typeof setInterval> | null>(null);
React.useEffect(() => {
timerRef.current = setInterval(() => {
console.log("tick");
}, 1000);
return () => {
if (timerRef.current) clearInterval(timerRef.current);
};
}, []);
return <p>Timer running...</p>;
}
// ── useReducer - typed state machine ─────────────────────────
type TaskState = {
tasks: Task[];
loading: boolean;
error: string | null;
};
type TaskAction =
| { type: "FETCH_START" }
| { type: "FETCH_SUCCESS"; payload: Task[] }
| { type: "FETCH_ERROR"; payload: string }
| { type: "ADD_TASK"; payload: Task }
| { type: "UPDATE_TASK"; payload: { id: number; changes: Partial<Task> } }
| { type: "DELETE_TASK"; payload: number };
function taskReducer(state: TaskState, action: TaskAction): TaskState {
switch (action.type) {
case "FETCH_START":
return { ...state, loading: true, error: null };
case "FETCH_SUCCESS":
return { tasks: action.payload, loading: false, error: null };
case "FETCH_ERROR":
return { ...state, loading: false, error: action.payload };
case "ADD_TASK":
return { ...state, tasks: [...state.tasks, action.payload] };
case "UPDATE_TASK":
return {
...state,
tasks: state.tasks.map((t) =>
t.id === action.payload.id ? { ...t, ...action.payload.changes } : t
),
};
case "DELETE_TASK":
return { ...state, tasks: state.tasks.filter((t) => t.id !== action.payload) };
default:
const _exhausted: never = action;
return state;
}
}
function TaskManager(): React.ReactElement {
const [state, dispatch] = React.useReducer(taskReducer, {
tasks: [], loading: false, error: null,
});
// dispatch is typed - only valid TaskAction shapes allowed:
dispatch({ type: "FETCH_START" }); // ✅
dispatch({ type: "DELETE_TASK", payload: 42 }); // ✅
// dispatch({ type: "DELETE_TASK", payload: "42" }); // ❌ payload must be number
return (
<div>
{state.loading && <p>Loading...</p>}
{state.error && <p className="error">{state.error}</p>}
<ul>{state.tasks.map((t) => <li key={t.id}>{t.title}</li>)}</ul>
</div>
);
}Common Mistakes
- Not annotating `useState<Task[]>([])` - TypeScript infers `never[]` from an empty array. Always annotate the generic when initialising with an empty array.
- `useRef<T>(null)` vs `useRef<T | null>(null)` - for DOM refs, use `useRef<HTMLInputElement>(null)` which gives `RefObject<T>` (`.current` is readonly and can be null). For mutable refs, use `useRef<number | null>(null)` to get `MutableRefObject`.
- Not handling `never` in reducer default - adding a new action type to the discriminated union without a case causes a compile error in the `never` default branch. This is the exhaustiveness check in action.
Tip
Tip
Practice Typed Hooks useState useReducer useRef in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Typed Hooks - useState, useReducer, useRef
Practice Task
Note
Practice Task - (1) Write a working example of Typed Hooks useState useReducer useRef from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Typed Hooks useState useReducer useRef is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- React hooks are generic.
- Not annotating `useState<Task[]>([])` - TypeScript infers `never[]` from an empty array. Always annotate the generic when initialising with an empty array.
- `useRef<T>(null)` vs `useRef<T | null>(null)` - for DOM refs, use `useRef<HTMLInputElement>(null)` which gives `RefObject<T>` (`.current` is readonly and can be null). For mutable refs, use `useRef<number | null>(null)` to get `MutableRefObject`.
- Not handling `never` in reducer default - adding a new action type to the discriminated union without a case causes a compile error in the `never` default branch. This is the exhaustiveness check in action.
Finished this lesson?