Typing useMemo and useCallback
You'll learn how TypeScript infers types for memoized values and callbacks—and when you need to step in.
The Core Idea
Both useMemo and useCallback usually infer their types automatically from what you return. TypeScript looks at your function's return value (for useMemo) or the callback itself (for useCallback) and figures out the type. You rarely need explicit annotations, but understanding when you do is the difference between clean code and confusing errors.
useMemo: Inferring the Memoized Value
const expensiveResult = useMemo(() => {
return items.filter(item => item.active).length;
}, [items]);
// Type: number (inferred from the return value)
TypeScript sees you return a number, so expensiveResult is typed as number. No annotation needed. If you return a complex object, that type is inferred too:
const config = useMemo(() => ({
theme: 'dark',
locale: 'en'
}), []);
// Type: { theme: string; locale: string }
When to annotate explicitly: If the inferred type is too broad (like string instead of a literal type), or you want to enforce a specific shape:
const config = useMemo<{ theme: 'dark' | 'light'; locale: string }>(() => ({
theme: 'dark',
locale: 'en'
}), []);
useCallback: Inferring Function Signatures
const handleClick = useCallback((id: number) => {
console.log(`Clicked ${id}`);
}, []);
// Type: (id: number) => void
The callback's parameter and return types define handleClick's type. You usually don't need to annotate—just type the parameters inside the callback itself.
Key Takeaway: TypeScript infers useMemo and useCallback types from your return values and function signatures; only add explicit type arguments when you need stricter types than inference provides.