Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/rerender-move-effect-to-event.md
1---2title: Put Interaction Logic in Event Handlers3impact: MEDIUM4impactDescription: avoids effect re-runs and duplicate side effects5tags: rerender, useEffect, events, side-effects, dependencies6---78## Put Interaction Logic in Event Handlers910If 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.1112**Incorrect (event modeled as state + effect):**1314```tsx15function Form() {16const [submitted, setSubmitted] = useState(false)17const theme = useContext(ThemeContext)1819useEffect(() => {20if (submitted) {21post('/api/register')22showToast('Registered', theme)23}24}, [submitted, theme])2526return <button onClick={() => setSubmitted(true)}>Submit</button>27}28```2930**Correct (do it in the handler):**3132```tsx33function Form() {34const theme = useContext(ThemeContext)3536function handleSubmit() {37post('/api/register')38showToast('Registered', theme)39}4041return <button onClick={handleSubmit}>Submit</button>42}43```4445Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)46