Lesson 4 of 8
Custom Hooks - Typed Reusable Logic
Custom hooks extract stateful logic into reusable typed functions. The return type of a custom hook is inferred - but for hooks returning tuples, a `as const` assertion or explicit return type is needed to prevent TypeScript from widening the tuple to an array.
Custom Hooks - Typed Return Values & Generics
// ── Custom hook - typed API fetching ─────────────────────────
interface UseAsyncState<T> {
data: T | null;
loading: boolean;
error: string | null;
refetch: () => void;
}
function useAsync<T>(
fetcher: () => Promise<T>,
deps: React.DependencyList = [],
): UseAsyncState<T> {
const [data, setData] = React.useState<T | null>(null);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState<string | null>(null);
const fetch = React.useCallback(async () => {
setLoading(true);
setError(null);
try {
const result = await fetcher();
setData(result);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
React.useEffect(() => { void fetch(); }, [fetch]);
return { data, loading, error, refetch: fetch };
}
// Usage - fully typed:
function TaskDetail({ id }: { id: number }): React.ReactElement {
const { data: task, loading, error } = useAsync(
() => taskApi.getById(id),
[id],
);
// task: Task | null
if (loading) return <p>Loading...</p>;
if (error) return <p className="error">{error}</p>;
if (!task) return <p>Task not found</p>;
return <h2>{task.title}</h2>; // ✅ task is Task here
}
// ── Tuple return - use const assertion or explicit type ───────
function useToggle(initial = false): [boolean, () => void] {
const [value, setValue] = React.useState(initial);
const toggle = React.useCallback(() => setValue((v) => !v), []);
return [value, toggle]; // explicit return type: [boolean, () => void]
}
// Without the explicit return type, TypeScript infers: (boolean | (() => void))[]
// - which allows [toggle, value] as a mistake. The tuple type prevents this.
const [isOpen, toggleOpen] = useToggle(false);
// isOpen: boolean ✅
// toggleOpen: () => void ✅
// ── useLocalStorage - generic typed storage ──────────────────
function useLocalStorage<T>(
key: string,
initialValue: T,
): [T, (value: T | ((prev: T) => T)) => void] {
const [stored, setStored] = React.useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? (JSON.parse(item) as T) : initialValue;
} catch {
return initialValue;
}
});
const setValue = React.useCallback(
(value: T | ((prev: T) => T)) => {
const next = value instanceof Function ? value(stored) : value;
setStored(next);
try {
window.localStorage.setItem(key, JSON.stringify(next));
} catch {}
},
[key, stored],
);
return [stored, setValue];
}
// Usage:
const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");Common Mistakes
- Tuple return typed as array - without `as const` or an explicit return type annotation, `[value, setter]` infers as `(boolean | (() => void))[]`. Destructuring then gives both elements the wrong type.
- Calling hooks conditionally - hooks must be at the top level of a component/hook. Conditional calls (`if (x) useEffect(...)`) violate the Rules of Hooks and cause undefined behavior.
- Not memoising fetcher functions passed to custom hooks - an inline arrow function as a dependency creates a new reference on every render and causes infinite loops. Use `useCallback` or pass stable references.
Tip
Tip
Practice Custom Hooks Typed Reusable Logic 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 Custom Hooks - Typed Reusable Logic
Practice Task
Note
Practice Task - (1) Write a working example of Custom Hooks Typed Reusable Logic 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 Custom Hooks Typed Reusable Logic 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
- Custom hooks extract stateful logic into reusable typed functions.
- Tuple return typed as array - without `as const` or an explicit return type annotation, `[value, setter]` infers as `(boolean | (() => void))[]`. Destructuring then gives both elements the wrong type.
- Calling hooks conditionally - hooks must be at the top level of a component/hook. Conditional calls (`if (x) useEffect(...)`) violate the Rules of Hooks and cause undefined behavior.
- Not memoising fetcher functions passed to custom hooks - an inline arrow function as a dependency creates a new reference on every render and causes infinite loops. Use `useCallback` or pass stable references.
Finished this lesson?