The 'Derived Trigger' Problem
What you'll learn: How to recognize when an effect fires on a state change that should instead trigger side effects directly where that state is set.
The Core Problem
The "derived trigger" problem happens when you use useEffect to respond to a state change, but that state change itself was caused by some user action or event. Instead of running side effects in the effect, you should handle them right where the state gets updated—in the event handler that caused the change.
Think of it like a chain reaction: User clicks button → State updates → Effect sees state change → Side effect runs. But you've added an unnecessary middle step. It should be: User clicks button → State updates + Side effect runs together.
The Antipattern
function Component() {
const [submitted, setSubmitted] = useState(false);
useEffect(() => {
if (submitted) {
analytics.track('form_submitted');
showToast('Success!');
}
}, [submitted]);
function handleSubmit() {
setSubmitted(true);
}
}
Here, submitted changes in handleSubmit, then the effect reacts to it. This is backwards! You already know why it changed—because the user submitted the form.
The Solution
function Component() {
const [submitted, setSubmitted] = useState(false);
function handleSubmit() {
setSubmitted(true);
analytics.track('form_submitted');
showToast('Success!');
}
}
Move the side effects into the event handler. They belong where the cause happens, not in a watcher that responds to the symptom.
Key Takeaway: If a state change has a known, specific cause (like a button click), handle side effects in that cause's event handler, not in a useEffect that watches for the state change afterward.