The Props-Change-Triggers-Effect Antipattern
You'll learn: Why using useEffect to respond to prop changes is usually a sign your component is designed incorrectly.
The Pattern That Smells
When you find yourself writing code like this, alarm bells should ring:
function UserProfile({ userId }) {
const [userData, setUserData] = useState(null);
useEffect(() => {
// Effect runs whenever userId changes
fetchUser(userId).then(setUserData);
}, [userId]);
return <div>{userData?.name}</div>;
}
At first glance, this seems logical: "When the userId prop changes, fetch new data." But this reveals a fundamental misunderstanding of React's component model.
Why It's Wrong
Props changing is the render. When userId changes, your component re-renders with the new value. The prop change isn't something that happens to your component—it is your component receiving new instructions.
Think of it like a vending machine: you don't press a button, then tell the machine to respond to that button press. The button press is the instruction. Similarly, new props are the instruction to your component.
The Real Problems
- Double rendering: Effect runs after render, causing a second render cycle
- Stale UI flash: The component briefly shows old data before the effect runs
- Wrong abstraction: You're treating synchronous data (props) as an asynchronous event
- Missing the point: If props should trigger actions, that logic belongs in the parent or in direct render logic
The Fix Depends on Context
- Deriving state? Compute during render, not in an effect
- Fetching data? Do it in the parent, or use Server Components
- External sync? Then
useEffectis appropriate (but rare)
Key Takeaway: If your effect runs "whenever props change," you're almost certainly using the wrong tool. Props changing means your component should render differently—not schedule a side effect.