Course contentsShow
← React
Lesson 2245 of 2,39649. Performance: Identifying ProblemsFree lesson

Using useMemo for Stable Object References

When and how to wrap object creation in useMemo to prevent unnecessary child re-renders.

Using useMemo for Stable Object References

You'll learn: How to wrap object creation in useMemo to prevent unnecessary child re-renders caused by new object references.

The Problem: Object Re-creation on Every Render

When you create an object inline during render (like const config = { theme: 'dark', size: 'large' }), JavaScript creates a new object every single time, even if the values inside haven't changed. Child components receiving this object as a prop see a different reference each time and re-render unnecessarily—even if they're wrapped in React.memo.

Think of it like handing someone a photocopy of a document instead of the same physical paper. Even though the content is identical, they see it as "different" because it's a new copy.

The Solution: useMemo

useMemo caches the object and only creates a new one when its dependencies change:

function Parent() {
  const config = useMemo(
    () => ({ theme: 'dark', size: 'large' }),
    [] // No dependencies = same object every render
  );

  return <Child config={config} />;
}

Now config maintains the same reference across renders, and Child won't re-render unless the dependencies change.

When Dependencies Matter

If the object's values do change, list them as dependencies:

function Parent({ theme }) {
  const config = useMemo(
    () => ({ theme, size: 'large' }),
    [theme] // New object only when theme changes
  );

  return <Child config={config} />;
}

When to Use This

Use useMemo for object props when:

  • The child is wrapped in React.memo
  • The object is passed to useEffect or useCallback dependencies
  • You've identified unnecessary renders in the Profiler

Key Takeaway: useMemo stabilizes object references by caching them between renders, preventing child components from seeing every render as a prop change and re-rendering unnecessarily.