useMemo for Derived Objects
What you'll learn: How to use useMemo to create stable object references when objects are computed from props or state, preventing unnecessary effect re-runs.
The Problem Recap
You've learned that inline objects cause infinite loops because they create new references every render. Moving objects outside helps, but what if the object must be computed from props or state? You can't move it outside then—it needs access to current values.
The useMemo Solution
useMemo lets you "freeze" a computed value between renders. It only recreates the object when specific dependencies change:
function UserProfile({ userId, theme }) {
// This config depends on props, but we want a stable reference
const config = useMemo(() => {
return {
id: userId,
darkMode: theme === 'dark'
};
}, [userId, theme]); // Only recreate when these change
useEffect(() => {
fetchUserData(config);
}, [config]); // Now config is stable unless userId or theme change
}
Without useMemo, the config object would be a new reference every render, triggering the effect constantly. With useMemo, it only changes when userId or theme change.
Think of It Like a Cache
useMemo is like telling React: "Remember this calculation. Only redo it if these inputs change." Between renders, React returns the same object reference from memory.
When to Use This
Use useMemo for derived objects when:
- The object is used as an effect dependency
- The object is computed from props/state
- Creating the object is expensive or causes unnecessary re-renders
Key Takeaway: useMemo creates stable object references from computed values, preventing dependency-related infinite loops while keeping your objects responsive to the data they depend on.