Stabilizing Effect Dependencies
What You'll Learn
You'll learn how useCallback and useMemo prevent infinite loops in useEffect by keeping dependency references stable across renders.
The Infinite Loop Problem
When you pass objects or functions to useEffect's dependency array, you can accidentally create an infinite loop. Here's why: if a dependency gets recreated on every render (new reference), useEffect fires, which might trigger a state update, causing a re-render, which recreates the dependency again, firing the effect... and the cycle never stops.
function UserProfile({ userId }) {
const [data, setData] = useState(null);
// ❌ This object is recreated every render
const options = { includeEmail: true };
useEffect(() => {
fetchUser(userId, options).then(setData);
// setData causes re-render → new options object → effect runs again!
}, [userId, options]); // 🔥 Infinite loop
}
Stabilizing with useMemo
Use useMemo to create a stable object reference that only changes when its dependencies change:
const options = useMemo(
() => ({ includeEmail: true }),
[] // Empty array = stable forever
);
Stabilizing with useCallback
Similarly, use useCallback to stabilize function references:
const handleSuccess = useCallback((result) => {
setData(result);
}, []); // Stable function reference
useEffect(() => {
fetchUser(userId).then(handleSuccess);
}, [userId, handleSuccess]); // ✅ handleSuccess never changes
When Dependencies Should Change
Sometimes you want the effect to re-run when a dependency changes—that's fine! The key is making those changes intentional by controlling what goes into the memoization dependency arrays.
Key Takeaway: Use useCallback and useMemo to stabilize objects and functions passed to useEffect dependencies, preventing unintended infinite loops while maintaining correct reactivity for values that should trigger re-runs.