556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / rerender-move-effect-to-event.md
1.2 KB
1--- 2title: Put Interaction Logic in Event Handlers 3impact: MEDIUM 4impactDescription: avoids effect re-runs and duplicate side effects 5tags: rerender, useEffect, events, side-effects, dependencies 6--- 7 8## Put Interaction Logic in Event Handlers 9 10If 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 15function Form() { 16 const [submitted, setSubmitted] = useState(false) 17 const theme = useContext(ThemeContext) 18 19 useEffect(() => { 20 if (submitted) { 21 post('/api/register') 22 showToast('Registered', theme) 23 } 24 }, [submitted, theme]) 25 26 return <button onClick={() => setSubmitted(true)}>Submit</button> 27} 28``` 29 30**Correct (do it in the handler):** 31 32```tsx 33function Form() { 34 const theme = useContext(ThemeContext) 35 36 function handleSubmit() { 37 post('/api/register') 38 showToast('Registered', theme) 39 } 40 41 return <button onClick={handleSubmit}>Submit</button> 42} 43``` 44 45Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)