Typing hooks and generic hooks
Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.
What you will be able to do
#- Type useState, useRef and useReducer.
- Write a generic custom hook.
- Type event handlers and callbacks.
Overview
#useState
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);
Without an argument the state type is inferred from the initial value; pass a type argument when the initial value is not representative.
useRef
const inputRef = useRef<HTMLInputElement>(null);
const valueRef = useRef<number>(0);
A ref initialized with null and a DOM type is a read-only ref object; a mutable ref holds a current value you can reassign.
useReducer
type State = { count: number };
type Action = { type: "inc" } | { type: "add"; amount: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "inc": return { count: state.count + 1 };
case "add": return { count: state.count + action.amount };
default: {
const exhaustive: never = action;
return exhaustive;
}
}
}
The discriminated action union makes the switch exhaustive; the default branch proves it by assigning the narrowed never, which the declared return type needs to compile.
Generic custom hook
function useToggle<T>(initial: T, next: T): [T, () => void] {
const [value, setValue] = useState(initial);
return [value, () => setValue(next)];
}
Event handlers
function onChange(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event.target.value);
}
Use the React event type rather than a hand-written shape.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement a generic `useToggle<T>(initial: T, next: T): [T, () => void]`.
starter.typescriptimport { useState } from "react"; export function useToggle<T>(initial: T, next: T): [T, () => void] { // your code }Reveal the reference answer
reference.typescriptimport { useState } from "react"; export function useToggle<T>(initial: T, next: T): [T, () => void] { const [value, setValue] = useState<T>(initial); return [value, () => setValue(next)]; }Authored expected output: Compiles with no errors. Runtime: calling the setter switches the value to next.
The generic T flows from the arguments into the state and the returned tuple.
Exercise 2Predict
What is the state type here? ```tsx const [items, setItems] = useState([]); ```
Exercise 3Debug
This fails because the action union is not narrowed. Fix the reducer. ```tsx type Action = { type: "inc" } | { type: "add"; amount: number }; function reducer(state: number, action: Action) { return state + action.amount; } ```
starter.typescripttype Action = { type: "inc" } | { type: "add"; amount: number }; function reducer(state: number, action: Action) { return state + action.amount; }Reveal the reference answer
reference.typescripttype Action = { type: "inc" } | { type: "add"; amount: number }; function reducer(state: number, action: Action) { return action.type === "add" ? state + action.amount : state + 1; }Authored expected output: Compile error resolved: Property 'amount' does not exist on type '{ type: "inc" }'. Narrowing on action.type fixes it.
The discriminant must be checked before the member is read.
Common misconceptions
#- useState infers the narrowest type from the initial value.
- useRef always returns a nullable ref.
- A reducer action can be any string.
Follow-up practice
#- typescript-api-client
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.