Sub topic 14
Typing hooks in TypeScript
This chapter assumes you can write the custom hooks from the earlier chapters in JavaScript and that you know basic TypeScript: type annotations, generics, union types, and as const. The goal is to give each hook a type signature that callers can read, that catches misuse at compile time, and that stays accurate as the hook changes.
Let the compiler infer what it can, and annotate the boundary
Inside a hook, TypeScript infers most types. useState(false) is already boolean, and useCallback keeps the type of the function you pass. The hook's public signature is where you add annotations. Parameters always need types. The return type is worth writing explicitly, because it is the contract callers depend on, and an accidental change to the body should not silently change it.
A hook has three common return shapes. The right shape decides how much typing work you need.
| Return shape | Example | Typing concern |
|---|---|---|
| Single value | `useDebouncedValue` | Make the type generic so it matches the input. |
| Tuple | `useToggle`, `useLocalStorage` | Stop TypeScript widening the tuple to an array. |
| Object | `useFetchJson` | Describe states that cannot coexist, usually with a discriminated union. |
Tuples: stop the array from widening
Here is the useToggle hook with no return type:
import { useState, useCallback } from 'react';
export function useToggle(initial: boolean = false) {
const [on, setOn] = useState<boolean>(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}TypeScript infers the return type as (boolean | (() => void))[]. That is an array of a union, not a pair. When a caller writes const [open, toggle] = useToggle(), both variables have the type boolean | (() => void). Calling toggle() is then a compile error, and the fix at the call site would be a cast.
You fix it in the hook, once. Either add as const to the returned array, or declare the return type. The declared type is the stronger choice because it documents the contract:
import { useState, useCallback } from 'react';
export function useToggle(initial: boolean = false): readonly [boolean, () => void] {
const [on, setOn] = useState<boolean>(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle] as const;
}The readonly modifier matches what as const produces. It also stops callers from writing result[0] = true, which would do nothing useful in a hook result anyway. A plain mutable [boolean, () => void] also works, but then as const would not be assignable to it, so pick one style per codebase.
Generics: let the caller's type flow through
A hook that handles values of any type should be generic. useDebouncedValue returns whatever type it receives:
import { useState, useEffect } from 'react';
export function useDebouncedValue<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState<T>(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}TypeScript infers T from the argument, so useDebouncedValue(query, 300) returns string when query is a string. Passing useState<T>(value) explicitly avoids a subtle problem. If T could be inferred as a literal type such as "a", state updates to other strings would be rejected.
State setters have a ready-made type. Use Dispatch<SetStateAction<T>> when your hook exposes a setter that behaves like the one from useState, so callers can pass either a value or an updater function:
import { useState, useEffect, type Dispatch, type SetStateAction } from 'react';
export function useLocalStorage<T>(
key: string,
initial: T,
): readonly [T, Dispatch<SetStateAction<T>>] {
const [value, setValue] = useState<T>(() => {
const raw = window.localStorage.getItem(key);
return raw === null ? initial : (JSON.parse(raw) as T);
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue] as const;
}The as T after JSON.parse is a cast, not a check. TypeScript cannot verify what is stored in the browser. If stored data can be stale or hand-edited, validate it with a schema library or a type guard before trusting it.
Objects: make impossible states impossible
The JavaScript useFetchJson returns { status, data, error }. Typed loosely, that would be { status: string; data: unknown; error: Error | null }, and every caller would have to guess which fields are valid. A discriminated union ties the fields to status:
import { useState, useEffect } from 'react';
type FetchState<T> =
| { status: 'loading'; data: null; error: null }
| { status: 'success'; data: T; error: null }
| { status: 'error'; data: null; error: Error };
export function useFetchJson<T>(url: string): FetchState<T> {
const [state, setState] = useState<FetchState<T>>({
status: 'loading',
data: null,
error: null,
});
useEffect(() => {
let ignore = false;
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<T>;
})
.then((data) => {
if (!ignore) setState({ status: 'success', data, error: null });
})
.catch((error: unknown) => {
if (ignore) return;
if (error instanceof DOMException && error.name === 'AbortError') return;
setState({
status: 'error',
data: null,
error: error instanceof Error ? error : new Error(String(error)),
});
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}Three details matter here:
- The
catchparameter is typedunknown, which is what TypeScript uses for caught values understrict. You must narrow it before reading.nameor.message. res.json()returnsPromise<any>. Theas Promise<T>is the one place the hook trusts the server. Callers chooseT, so the type is a promise about the response shape, not proof of it.- The
ignoreflag andAbortControllerare unchanged from the JavaScript version. Typing does not replace race-condition handling.
A caller narrows by checking status:
import { useFetchJson } from './useFetchJson';
type User = { id: number; name: string };
export function UserCard({ id }: { id: number }) {
const state = useFetchJson<User>(`/api/users/${id}`);
if (state.status === 'loading') return <p>Loading…</p>;
if (state.status === 'error') return <p>{state.error.message}</p>;
return <h2>{state.data.name}</h2>;
}After the two early returns, TypeScript knows state.data is a User, not User | null. Without the union you would write state.data!.name or add redundant checks.
Typing hooks that touch the DOM
Refs need an explicit type argument because TypeScript cannot guess which element you will attach them to. A hook that returns a ref should let the caller choose the element type:
import { useRef, useEffect } from 'react';
export function useFocusOnMount<T extends HTMLElement>() {
const ref = useRef<T>(null);
useEffect(() => {
ref.current?.focus();
}, []);
return ref;
}The caller writes const ref = useFocusOnMount<HTMLInputElement>() and passes ref to an <input>. The extends HTMLElement constraint makes .focus() available and rejects non-element types.
For event hooks, you can tie the handler's parameter to the event name by using the browser's event map. The K extends keyof WindowEventMap generic links the two:
import { useEffect, useRef } from 'react';
export function useWindowEvent<K extends keyof WindowEventMap>(
type: K,
handler: (event: WindowEventMap[K]) => void,
): void {
const handlerRef = useRef(handler);
useEffect(() => {
handlerRef.current = handler;
});
useEffect(() => {
const listener = (event: WindowEventMap[K]) => handlerRef.current(event);
window.addEventListener(type, listener);
return () => window.removeEventListener(type, listener);
}, [type]);
}Calling useWindowEvent('keydown', (e) => e.key) gives e the type KeyboardEvent. Calling useWindowEvent('resize', (e) => e.key) is a compile error, because a resize event has no key. This version listens on window only. Supporting an arbitrary target needs overloads, because HTMLElementEventMap and WindowEventMap are different maps.
Gotchas
- Optional parameters become a mess in tuples. If a hook takes an options object, give the object its own type and default it:
options: Options = {}. Avoid long lists of optional positional parameters. - Do not export
anythrough a hook. A hook is called from many places, so a loose type spreads. Useunknownand make callers narrow. - Inferred return types can leak internals. If the hook returns an object literal, a later edit that adds a field widens the public API without any review. A named return type makes the change visible.
useRefoverloads differ by version.useRef<T>(null)gives a read-onlycurrentin React 18's types, and a mutable one in React 19's types. Check your installed@types/reactifref.current = xfails to compile.- Generics cannot be inferred from nothing.
useFetchJson(url)with no type argument infersTasunknown. Require callers to passT, or accept a parser function and inferTfrom its return type.
Exercise
A teammate writes export function useCounter(start = 0) { const [n, setN] = useState(start); const inc = () => setN(n + 1); return [n, inc]; } in TypeScript. A component calls const [count, inc] = useCounter(); and then inc(), and the compiler reports that the expression is not callable. What causes this, and what is the smallest change in the hook that fixes it?
Show answer
The return value [n, inc] is inferred as (number | (() => void))[], an array of a union, so inc has the type number | (() => void) and cannot be called. Fix it in the hook by adding as const to the returned array, or better by declaring the return type readonly [number, () => void] and returning [n, inc] as const. The call site then needs no change.
Exercise
You change useFetchJson so that it returns { status: string; data: T | null; error: Error | null } instead of a discriminated union. What does a caller lose, and how does it show up in the component code?
Show answer
The caller loses narrowing. After checking state.status === 'success', TypeScript still sees state.data as T | null, because status is a plain string and is not linked to the other fields. The component then needs a non-null assertion (state.data!.name) or an extra if (state.data) check, and nothing stops a bug where status says 'success' but data is null.