Extracting Primitive Values from Objects
What You'll Learn
You'll learn how to depend on specific properties of an object in your dependency arrays instead of the entire object, preventing unnecessary re-executions of useMemo and useCallback.
The Object Dependency Problem Revisited
In the previous lesson, you learned that objects cause memoization to break because they're compared by reference. Even if an object's contents stay the same, a new object instance triggers re-execution.
The solution? Don't depend on the object—depend on the specific primitive values you actually use.
Extracting What You Need
Instead of putting an entire object in your dependency array, extract the primitive properties beforehand:
// ❌ Bad: Depends on entire object
const fullName = useMemo(() => {
return `${user.firstName} ${user.lastName}`;
}, [user]); // Re-runs whenever user object changes
// ✅ Good: Depends on specific primitives
const firstName = user.firstName;
const lastName = user.lastName;
const fullName = useMemo(() => {
return `${firstName} ${lastName}`;
}, [firstName, lastName]); // Only re-runs when these strings change
Why This Works
Primitives (strings, numbers, booleans) are compared by value, not reference. If user.firstName is "Sarah" in both renders, React sees them as equal—even if the user object itself is new.
The Pattern
- Destructure or extract the specific properties outside the hook
- Use those primitives inside your memoized function
- List only those primitives in the dependency array
const { id, status } = order;
const isProcessable = useMemo(() => {
return status === 'pending' && id > 1000;
}, [id, status]); // Precise dependencies
Key Takeaway: Extract and depend on primitive property values instead of entire objects to make your memoization stable and effective.