Course contentsShow
← React
Lesson 664 of 2,39618. When NOT to Use useEffectFree lesson

The useEffect Anti-pattern for Derived State

Why using useEffect to sync state based on other state creates unnecessary complexity and bugs.

The useEffect Anti-pattern for Derived State

You'll learn why syncing state with useEffect based on other state is a common but harmful mistake.

The Antipattern in Action

Many developers instinctively reach for useEffect when they need one piece of state to "follow" another:

function UserGreeting({ firstName, lastName }) {
  const [fullName, setFullName] = useState('');

  // ❌ ANTIPATTERN: Using effect to sync derived state
  useEffect(() => {
    setFullName(`${firstName} ${lastName}`);
  }, [firstName, lastName]);

  return <h1>Hello, {fullName}!</h1>;
}

Why This Creates Problems

1. Double Rendering: The component renders with stale fullName, then the effect runs and triggers a second render with the correct value. Your users see a flicker or outdated data momentarily.

2. Unnecessary Complexity: You're maintaining extra state (fullName) and synchronization logic when the value can simply be calculated.

3. Potential Bugs: If you forget a dependency or calculate incorrectly, your derived state becomes inconsistent with the source data.

The Correct Approach

Just compute it during render:

function UserGreeting({ firstName, lastName }) {
  // ✅ CORRECT: Calculate directly during render
  const fullName = `${firstName} ${lastName}`;

  return <h1>Hello, {fullName}!</h1>;
}

No useState, no useEffect, no extra renders. The value is always in sync because it's derived from the source of truth, not stored separately.

Think of it like this: you wouldn't use useEffect to set a variable to 2 + 2 every time numbers change—you'd just write const result = 2 + 2. The same logic applies to state.

Key Takeaway: If you can calculate a value from existing props or state during render, do that instead of storing it in state and syncing with useEffect. Save effects for synchronizing with external systems, not internal calculations.