Sub topic 14
Typing Hooks in TypeScript
This chapter assumes you know useState, useCallback, and the basics of TypeScript: type annotations, generics, and tuples. You have already written hooks such as useToggle in JavaScript. Here you add types so that callers get accurate autocomplete and errors.
Why hooks need explicit return types
TypeScript infers the return type of a function from its return statement. When a hook returns [on, toggle], the inferred type is an array, not a pair. The element type becomes the union of everything in it.
import { useState, useCallback } from 'react';
export function useToggleLoose(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle]; // inferred: (boolean | (() => void))[]
}A caller who writes const [open, toggle] = useToggleLoose() gets open typed as boolean | (() => void). Calling toggle() is then a type error, because TypeScript cannot tell which element is the function.
Returning a tuple
There are two ways to fix this. You can annotate the return type, or you can add as const to the returned array. The typed useToggle does both.
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 tuple type fixes the position of each element. on is a boolean and toggle is a function. The readonly modifier also stops callers from mutating the returned array.
If a hook returns an object instead, no tuple is needed. Property names already carry the types.
Typing generic hooks
Some hooks work with any value type. Use a generic parameter so the type flows from input to output. A debounced value has the same type as the value it came from.
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;
}
const query = useDebouncedValue('react', 300); // stringTypeScript infers T from the argument, so callers rarely write <string> themselves.
Typing state that starts empty
A data-loading hook starts without data, so its state is a union. Model each status as its own member of a discriminated union. This lets TypeScript narrow the type after a check.
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: Error) => {
if (!ignore && error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}A component can now check state.status === 'success' and TypeScript knows state.data is T and not null.
Common errors
- The generic cannot be inferred.
useFetchJson(url)givesTasunknown. Pass it explicitly:useFetchJson<User[]>(url). The type is a promise about the server response. TypeScript does not check it at runtime. - A missing
as const. Without the annotation oras const, a tuple widens to an array of a union. useState(null)without a type argument. The state is typed asnullonly, and latersetState(value)calls fail. WriteuseState<User | null>(null).- Refs that start as
null. UseuseRef<HTMLDivElement>(null)for DOM refs, anduseRef<T>(initial)for values you mutate.
Exercise
A hook ends with return [value, setValue]. Callers report that value has the type string | ((v: string) => void). Give two ways to fix it.
Show answer
Annotate the return type as a tuple, for example readonly [string, (v: string) => void], or write return [value, setValue] as const. Either one makes TypeScript treat the result as a fixed-length tuple, so each position keeps its own type.
Exercise
Why does FetchState<T> use a status field with literal types instead of a single object with data: T | null and error: Error | null?
Show answer
The literal status makes the type a discriminated union. After checking state.status === 'success', TypeScript narrows state so data is T and not null. With one loose object, every field stays nullable and callers need extra checks.