useMemo for Stable Object References
You'll learn: How to use useMemo to prevent objects and arrays from changing identity on every render, keeping dependency arrays and props stable.
The Object Reference Problem
In JavaScript, {} creates a new object every time, even if the contents look identical. This matters because React's dependency arrays use referential equality (===) to detect changes. When you create an object inline during render, it gets a brand new reference each time:
function UserProfile({ userId }) {
const options = { id: userId, detailed: true }; // New object every render!
useEffect(() => {
fetchUser(options);
}, [options]); // This runs every single render
}
Even though options looks the same, it's a different object each time UserProfile renders.
The useMemo Solution
Wrap object creation in useMemo to preserve the same reference across renders until dependencies actually change:
function UserProfile({ userId }) {
const options = useMemo(() => {
return { id: userId, detailed: true };
}, [userId]); // New object only when userId changes
useEffect(() => {
fetchUser(options);
}, [options]); // Stable reference!
}
Now options keeps the same identity until userId changes. Your effect runs only when it should.
Arrays Need This Too
The same applies to arrays:
const filters = useMemo(() => ['active', 'pending'], []); // Stable array
const ids = useMemo(() => [userId, teamId], [userId, teamId]); // Updates when inputs change
Key Takeaway: Use useMemo to create stable object and array references when those values are used in dependency arrays or passed as props to memoized components—otherwise React sees them as "new" every render even when their contents haven't changed.