Hello! Welcome back to our module on performance optimization in React.
In our previous lessons, we explored React.memo, useMemo, and useCallback as powerful tools for preventing unnecessary re-renders and computations. You learned how to memoize components, values, and functions. As promised, this lesson is a dedicated deep dive into applying TypeScript to these hooks, plus the useRef hook, to ensure your optimizations are not only effective but also type-safe and robust.
Today, you will master the specific TypeScript patterns for useRef, useMemo, and useCallback. This will help you write cleaner, more predictable code and catch potential bugs at compile time rather than runtime.
Typing the useRef Hook
The useRef hook is versatile, and its typing depends on its two primary use cases: accessing a DOM element or storing a mutable value that persists across renders. TypeScript requires us to handle these two cases differently.
Let's explore the nuances of each.
Hooks | React TypeScript Cheatsheets
To start, let's read the definitive guide on this topic from the 'React TypeScript Cheatsheets'. It provides a clear and detailed breakdown of how to type both DOM refs and mutable value refs.
Read the section titled 'useRef'. Pay close attention to the distinction between 'Option 1: DOM element ref' and 'Option 2: Mutable value ref'. Note how the initial value (null vs. a concrete value) changes the type of the returned ref object.
1. Typing DOM Element Refs
As the cheatsheet explains, when you want a reference to a DOM element, you should initialize the ref with null. This is because the element doesn't exist in the DOM until after the component mounts.
The TypeScript pattern is: useRef<ElementType>(null).
ElementType: Be as specific as possible (e.g.,HTMLInputElement,HTMLDivElement,HTMLButtonElement). This gives you access to element-specific properties and methods like.focus()or.play().nullinitial value: This creates a union type for the ref's current property:ElementType | null.
Because .current can be null, you must use a type guard to access it safely.
import React, { useRef, useEffect } from 'react';
function MyInput() {
// The ref's type is React.RefObject<HTMLInputElement>
// The type of inputRef.current is HTMLInputElement | null
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// Safe access with a type guard
if (inputRef.current) {
inputRef.current.focus();
}
// Alternative: optional chaining
inputRef.current?.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
2. Typing Mutable Value Refs
When using useRef to store a mutable value (like an instance variable in a class), you typically initialize it with a starting value.
The TypeScript pattern is: useRef<ValueType>(initialValue).
If the initial value is not null, the .current property will be typed simply as ValueType, and you can read or write to it directly without null checks. This is useful for storing timer IDs, previous state values, or any other data that needs to persist without causing re-renders.

import React, { useRef, useEffect } from 'react';
function Timer() {
// The ref's type is React.MutableRefObject<number | null>
// We can initialize with null if we don't have an ID yet.
const intervalRef = useRef<number | null>(null);
useEffect(() => {
// We can directly assign to .current
intervalRef.current = window.setInterval(() => {
console.log('Timer tick!');
}, 1000);
// Cleanup function
return () => {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
}
};
}, []);
return <div>Check the console for timer ticks.</div>;
}
Now, let's watch a video that demonstrates these useRef typing concepts in a practical coding session.
Learn React Hooks with Typescript
The video 'Learn React Hooks with Typescript' by Dave Gray includes a great segment on useRef.
Watch the segment from 16:17 to 22:26. The presenter demonstrates how to create a ref for an input element, type it with HTMLInputElement, and handle the initial null value using optional chaining for safe access.
Test your understanding!
You are building a video player component. You need to create a ref to the <video> element so you can programmatically call its .play() method from a button click. How would you declare and type this ref?
import React, { useRef } from 'react';
const VideoPlayer = () => {
// How do you declare and type the videoRef?
// const videoRef = ...
const handlePlay = () => {
// How do you safely call the play method?
};
return (
<div>
<video ref={videoRef} src="my-video.mp4" width="300" />
<button onClick={handlePlay}>Play</button>
</div>
);
};
Show answer
You should type the ref with HTMLVideoElement and initialize it with null. Then, use optional chaining or a null check to safely call .play().
import React, { useRef } from 'react';
const VideoPlayer = () => {
const videoRef = useRef<HTMLVideoElement>(null);
const handlePlay = () => {
// Safely call the play method using optional chaining
videoRef.current?.play();
};
return (
<div>
<video ref={videoRef} src="my-video.mp4" width="300" />
<button onClick={handlePlay}>Play</button>
</div>
);
};
Typing useMemo and useCallback
For useMemo and useCallback, TypeScript's inference is often quite good. However, explicitly defining types can improve clarity and catch subtle bugs, especially in complex scenarios.
TypeScript for React Developers: 12 Common Mistakes ...
The article 'TypeScript for React Developers' has a concise section on common mistakes and best practices for these hooks.
Read 'Mistake 9: useMemo and useCallback type inference issues'. It explains why explicit typing can be necessary and shows the syntax for both hooks.
Let's watch a practical demonstration of typing both hooks.
Learn React Hooks with Typescript
We'll return to Dave Gray's video, which covers useCallback and useMemo back-to-back.
Watch from 07:01 to 16:28. The first part (07:01 - 12:30) covers useCallback. Note how event types like MouseEvent and KeyboardEvent are explicitly defined for the function's parameters. The second part (12:17 - 16:28) covers useMemo. Observe how an explicit return type (number in this case) can be provided to the useMemo hook using a generic parameter: useMemo<number>(...).
Typing useMemo
As the video shows, you can provide an explicit return type to useMemo using a generic argument. This is helpful when the memoized value has a complex object shape, ensuring the rest of your component consumes it correctly.
Syntax: useMemo<ReturnType>(() => ..., deps)
type User = { id: number; name: string };
const users: User[] = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
// Explicitly type the return value as an array of strings.
const userNames = useMemo<string[]>(() => {
return users.map(user => user.name);
}, [users]);
// userNames is now correctly typed as string[]
Typing useCallback
Typing useCallback is like typing any function expression. You define types for its parameters and, if necessary, its return value. This is especially important for event handlers, where providing the correct React.Event type gives you type safety and autocompletion on event properties like event.target.value.
Syntax: useCallback((param: Type): ReturnType => { ... }, deps)
import React, { useState, useCallback } from 'react';
const SearchComponent = () => {
const [query, setQuery] = useState('');
// Explicitly type the event parameter
const handleInputChange = useCallback((event: React.ChangeEvent<HTMLInputElement>): void => {
setQuery(event.target.value);
}, []); // No dependencies, as setQuery is stable
return <input type="text" value={query} onChange={handleInputChange} />;
};
A useful note from the "React TypeScript Cheatsheets" is that since React 18, function parameters in useCallback that are not explicitly typed will cause a compile error (Parameter 'e' implicitly has an 'any' type.). This encourages you to type your handlers correctly from the start.
Test your understanding!
You are creating a memoized callback function that takes a numeric id and a name string, and then calls an API. How would you correctly type this useCallback hook?
import { useCallback } from 'react';
function useUpdateUser() {
const apiCall = (id: number, name: string) => { /* ... */ };
// How would you type this useCallback?
const handleUpdate = useCallback(
(id, name) => {
console.log(`Updating user ${id} to name ${name}`);
apiCall(id, name);
},
[]
);
return handleUpdate;
}
Show answer
You should add type annotations for the id and name parameters and specify the return type, which is void in this case.
import { useCallback } from 'react';
function useUpdateUser() {
const apiCall = (id: number, name: string) => { /* ... */ };
const handleUpdate = useCallback(
(id: number, name: string): void => {
console.log(`Updating user ${id} to name ${name}`);
apiCall(id, name);
},
[] // Assuming apiCall is stable and defined outside the component
);
return handleUpdate;
}
Conclusion
You've now integrated TypeScript with React's key performance and reference hooks. This discipline ensures that as your application grows, your optimizations remain predictable and free of type-related errors.
Key Takeaways:
useRefTyping:- For DOM elements:
useRef<ElementType>(null). Always check fornullbefore accessing.current. - For mutable values:
useRef<ValueType>(initialValue). No null check is needed if the initial value isn't null.
- For DOM elements:
useMemoTyping:- Use a generic to be explicit about the return type:
useMemo<ReturnType>(...). This is most useful for complex objects or arrays.
- Use a generic to be explicit about the return type:
useCallbackTyping:- Type it like a standard function expression, specifying parameter and return types:
useCallback((param: Type): ReturnType => ..., deps). - Pay special attention to React's synthetic event types (
React.ChangeEvent,React.MouseEvent, etc.).
- Type it like a standard function expression, specifying parameter and return types:
Preview of the Next Lesson:
Our journey into performance optimization isn't over. In the next lesson, "Optimize Context consumers by splitting contexts or memoizing provider values," we will tackle one of the most common sources of performance issues in large React applications. You'll find that the skills you've just honed—especially using useMemo to stabilize objects passed as context values—are absolutely essential for preventing unnecessary re-renders of entire component subtrees.