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-functional-setstate.md
1---2title: Use Functional setState Updates3impact: MEDIUM4impactDescription: prevents stale closures and unnecessary callback recreations5tags: react, hooks, useState, useCallback, callbacks, closures6---78## Use Functional setState Updates910When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.1112**Incorrect (requires state as dependency):**1314```tsx15function TodoList() {16const [items, setItems] = useState(initialItems)1718// Callback must depend on items, recreated on every items change19const addItems = useCallback((newItems: Item[]) => {20setItems([...items, ...newItems])21}, [items]) // ❌ items dependency causes recreations2223// Risk of stale closure if dependency is forgotten24const removeItem = useCallback((id: string) => {25setItems(items.filter(item => item.id !== id))26}, []) // ❌ Missing items dependency - will use stale items!2728return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />29}30```3132The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.3334**Correct (stable callbacks, no stale closures):**3536```tsx37function TodoList() {38const [items, setItems] = useState(initialItems)3940// Stable callback, never recreated41const addItems = useCallback((newItems: Item[]) => {42setItems(curr => [...curr, ...newItems])43}, []) // ✅ No dependencies needed4445// Always uses latest state, no stale closure risk46const removeItem = useCallback((id: string) => {47setItems(curr => curr.filter(item => item.id !== id))48}, []) // ✅ Safe and stable4950return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />51}52```5354**Benefits:**55561. **Stable callback references** - Callbacks don't need to be recreated when state changes572. **No stale closures** - Always operates on the latest state value583. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks594. **Prevents bugs** - Eliminates the most common source of React closure bugs6061**When to use functional updates:**6263- Any setState that depends on the current state value64- Inside useCallback/useMemo when state is needed65- Event handlers that reference state66- Async operations that update state6768**When direct updates are fine:**6970- Setting state to a static value: `setCount(0)`71- Setting state from props/arguments only: `setName(newName)`72- State doesn't depend on previous value7374**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.75