Course contentsShow
← React
Lesson 636 of 2,39617. Common useEffect MistakesFree lesson

Moving Objects Outside the Component

Extract constant objects outside the component scope to maintain stable references across renders.

Moving Objects Outside the Component

What you'll learn: How moving constant objects outside your component prevents unnecessary effect re-runs caused by reference instability.

The Problem with Objects Defined Inside Components

When you define an object or array inside your component body, React creates a brand new reference on every render—even if the contents are identical. Since useEffect compares dependencies by reference, not value, it sees a "different" object each time and re-runs unnecessarily.

function UserProfile() {
  const defaultOptions = { theme: 'dark', lang: 'en' }; // ❌ New object every render

  useEffect(() => {
    configureSettings(defaultOptions);
  }, [defaultOptions]); // This runs on EVERY render!
}

The Solution: Move Constants Outside

If an object or array never changes and doesn't depend on props or state, move it outside the component entirely:

const DEFAULT_OPTIONS = { theme: 'dark', lang: 'en' }; // ✅ Created once

function UserProfile() {
  useEffect(() => {
    configureSettings(DEFAULT_OPTIONS);
  }, [DEFAULT_OPTIONS]); // Same reference every render—runs once!
}

Why This Works

Think of it like a library card. If you get a new card with the same number every time you visit, the library system thinks you're a different person each visit. But if you keep the same physical card, they recognize you immediately.

By defining the object outside the component, JavaScript creates it once when the module loads, not on every render. The reference stays stable, so your effect only runs when it truly needs to.

When to Use This Pattern

  • Configuration objects that never change
  • API endpoint URLs
  • Default form values
  • Static filter/sort options

Key Takeaway: Extract constant objects and arrays outside your component to maintain stable references and prevent unnecessary effect re-runs triggered by dependency array comparisons.