| 1 | --- |
| 2 | title: Put Interaction Logic in Event Handlers |
| 3 | impact: MEDIUM |
| 4 | impactDescription: avoids effect re-runs and duplicate side effects |
| 5 | tags: rerender, useEffect, events, side-effects, dependencies |
| 6 | --- |
| 7 | |
| 8 | ## Put Interaction Logic in Event Handlers |
| 9 | |
| 10 | If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action. |
| 11 | |
| 12 | **Incorrect (event modeled as state + effect):** |
| 13 | |
| 14 | ```tsx |
| 15 | function Form() { |
| 16 | const [submitted, |
| 17 | const theme = |
| 18 | |
| 19 | useEffect(() => |
| 20 | if (submitted) { |
| 21 | post("/api/register"); |
| 22 | showToast("Registered", |
| 23 | } |
| 24 | }, [submitted, |
| 25 | |
| 26 | return <button onClick |
| 27 | } |
| 28 | ``` |
| 29 | |
| 30 | **Correct (do it in the handler):** |
| 31 | |
| 32 | ```tsx |
| 33 | function Form() { |
| 34 | const theme = |
| 35 | |
| 36 | function handleSubmit() { |
| 37 | post("/api/register"); |
| 38 | showToast("Registered", |
| 39 | } |
| 40 | |
| 41 | return <button onClick |
| 42 | } |
| 43 | ``` |
| 44 | |
| 45 | Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler |