Part 06 / Topic 7 of 7
When NOT to use an effect: events vs. effects
An effect's job is to synchronize a component with something outside React, as a consequence of rendering with some props/state. A click is not that - it is already an event, and React already calls your handler at exactly the right moment. Routing it through a state flag and an effect instead of handling it directly is not just more code; it is a real bug waiting to happen. examples/06_effect_vs_handler_for_events.jsx's AddToCartLoggerBroken tries to log an analytics event "when shouldLog becomes true":
// examples/06_effect_vs_handler_for_events.jsx
export function AddToCartLoggerBroken({ itemName, onLog }) {
const [shouldLog, setShouldLog] = useState(false);
useEffect(() => {
if (shouldLog) {
onLog(itemName);
}
// BUG: shouldLog is never reset back to false here
}, [shouldLog, itemName, onLog]);
return <button onClick={() => setShouldLog(true)}>Add {itemName} to cart</button>;
}
The first click flips shouldLog from false to true - a real change, so React rerenders and the effect fires, logging once. The second click calls setShouldLog(true) again - but shouldLog is already true, so this is not a change at all. React skips the rerender entirely, which means the effect never runs a second time, which means the second (and every later) click is silently never logged. Clicking the broken button three times in a row really logs exactly once (examples/06_effect_vs_handler_for_events.test.jsx). AddToCartLoggerFixed deletes the state and the effect entirely:
// examples/06_effect_vs_handler_for_events.jsx
export function AddToCartLoggerFixed({ itemName, onLog }) {
return <button onClick={() => onLog(itemName)}>Add {itemName} to cart</button>;
}
Three clicks on the fixed version really log three times - once per click, exactly as intended, with no flag and no effect to get wrong.
Done here? The practice set for Part 6 — including the solutions — is on the part page.