The Inline Object Antipattern
In this lesson: You'll understand why writing { key: value } directly in a dependency array triggers infinite re-renders.
The Problem in Plain English
When you create an object using the {} syntax, JavaScript creates a brand new object in memory every time, even if the contents look identical. Remember from earlier lessons that objects are compared by reference, not by value.
So when you write:
useEffect(() => {
// do something with options
}, [{ theme: 'dark' }]);
...React sees a different object on every render, even though { theme: 'dark' } "looks" the same each time. This makes React think the dependency changed, so it runs your effect again. That effect might trigger a state update, causing another render, which creates another new object, which triggers the effect again... infinite loop.
The Antipattern in Action
This is the mistake:
useEffect(() => {
console.log('Effect ran!');
}, [{ userId: 123 }]); // 🚨 New object every render!
Every render, { userId: 123 } is a fresh object. React compares it to the previous object using Object.is(), which checks if they're the same object in memory. They're not, so the effect re-runs forever.
The Fix
Move the object creation outside the component (if it's static) or memoize it with useMemo (if it depends on props/state):
// Static: move outside
const options = { userId: 123 };
// Then use it:
useEffect(() => {
// ...
}, [options]); // ✅ Same reference every render
Key Takeaway: Never create objects inline (with {}) directly in a dependency array—each render creates a new reference, triggering infinite loops.