The useMemo Hook Signature
You'll learn the exact structure of useMemo: what it takes as arguments and what it returns.
Understanding the Two-Argument Structure
The useMemo hook takes exactly two arguments:
- A creation function that computes and returns the value you want to memoize
- A dependency array that tells React when to recompute that value
Here's the basic signature:
const memoizedValue = useMemo(() => {
// Compute and return your expensive value
return someExpensiveComputation();
}, [dependency1, dependency2]);
The Creation Function
The first argument is a function that runs the computation and returns the result. This function has no parameters—it just does its work and gives back a value. React will call this function initially and then only again when dependencies change.
Think of it like a recipe: the creation function contains the step-by-step instructions for making your value.
The Dependency Array
The second argument is an array listing the values your computation depends on. React compares these values between renders. If they haven't changed, React skips running the creation function and returns the previous result from memory.
This is exactly like the dependency array you've used with other hooks—same rules apply.
What useMemo Returns
useMemo doesn't return a function—it returns the actual value that your creation function produced. This is a key difference from other hooks you'll encounter later.
Key Takeaway: useMemo takes a creation function that returns a value and a dependency array, then returns the memoized result—only recomputing when dependencies change.