Skip to main content
rule CX Codex

rerender-functional-setstate — Claude Code rule for React state

The rerender-functional-setstate rule recommends functional state updates when the next React value depends on the current one. It helps callbacks avoid stale state and unnecessary dependencies.

MIT ★ 7,191 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/rerender-functional-setstate.md
Open on GitHub

What rerender-functional-setstate does

When a state change needs the previous value, the rule favors passing an updater function to setState rather than reading the state variable directly. The examples cover callbacks built with useCallback, event handlers, and asynchronous updates.

With this form, a callback can update a list without capturing the list state in its dependency array. Direct references can make the callback get recreated whenever state changes; forgetting a dependency can leave it using an old value. Static assignments such as setCount(0) do not need an updater. React Compiler can optimize some cases automatically, but the rule still recommends functional updates for correctness.

What it helps with

  • Update state from its current value
  • Remove a state dependency from useCallback
  • Prevent callbacks from reading stale state
  • Keep callback references stable as state changes

Example prompts for the agent

  • Review the state update in TodoList and use an updater function wherever it depends on the current value.
  • Fix the item-removal callback so it filters the latest list state.
  • Check whether this event handler calculates its next state from the previous one.

How to install rerender-functional-setstate

Manually: put the files in place

.claude/rules/rerender-functional-setstate.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about rerender-functional-setstate

How do I install rerender-functional-setstate in Claude Code?

Add the rule at .claude/rules/rerender-functional-setstate.md.

What does rerender-functional-setstate do?

It recommends updater functions for state changes that rely on the current value. This helps avoid stale closures and unnecessary callback dependencies.

Should I use functional updates with React Compiler enabled?

React Compiler can optimize some cases automatically. The rule still recommends functional updates for correctness and to avoid stale closures.

Source text

rerender-functional-setstate.md · MIT
---
title: Use Functional setState Updates
impact: MEDIUM
impactDescription: prevents stale closures and unnecessary callback recreations
tags: react, hooks, useState, useCallback, callbacks, closures
---

## Use Functional setState Updates

When 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.

**Incorrect (requires state as dependency):**

```tsx
function TodoList() {
  const [items, setItems] = useState(initialItems)
  
  // Callback must depend on items, recreated on every items change
  const addItems = useCallback((newItems: Item[]) => {
    setItems([...items, ...newItems])
  }, [items])  // ❌ items dependency causes recreations
  
  // Risk of stale closure if dependency is forgotten
  const removeItem = useCallback((id: string) => {
    setItems(items.filter(item => item.id !== id))
  }, [])  // ❌ Missing items dependency - will use stale items!
  
  return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```

The 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.

**Correct (stable callbacks, no stale closures):**

```tsx
function TodoList() {
  const [items, setItems] = useState(initialItems)
  
  // Stable callback, never recreated
  const addItems = useCallback((newItems: Item[]) => {
    setItems(curr => [...curr, ...newItems])
  }, [])  // ✅ No dependencies needed
  
  // Always uses latest state, no stale closure risk
  const removeItem = useCallback((id: string) => {
    setItems(curr => curr.filter(item => item.id !== id))
  }, [])  // ✅ Safe and stable
  
  return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```

**Benefits:**

1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **Prevents bugs** - Eliminates the most common source of React closure bugs

**When to use functional updates:**

- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state

**When direct updates are fine:**

- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value

**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.

© tech-leads-club · MIT · tech-leads-club/agent-skills

Similar IDE rules

All IDE rules for Frontend and UI →

From the same set130

The whole set →
patterns-explicit-variants patterns-explicit-variants — a rule that pushes one component per mode instead of a single component buried under boolean props. The call site then says what renders. CX Codex +1 ★ 7,191repo stars async-suspense-boundaries async-suspense-boundaries guides Claude Code to place data fetching behind Suspense boundaries so headers, sidebars, and layout shells render without blocking. CX Codex +1 ★ 7,191repo stars architecture-compound-components The architecture-compound-components rule describes splitting complex UI components into pieces that share state through context. It fits components that have accumulated render props and conditional options. CX Codex +1 ★ 7,191repo stars state-decouple-implementation state-decouple-implementation — a Claude Code rule that keeps state management inside providers and exposes only a context interface to UI components. Swap useState for Zustand or a server sync without touching a single UI file. CX Codex +1 ★ 7,191repo stars state-lift-state state-lift-state — a Claude Code rule that moves React state into a provider component, so siblings outside the main UI read and update it without prop drilling or refs. CX Codex +1 ★ 7,191repo stars js-batch-dom-css js-batch-dom-css prevents layout thrashing by separating style updates from layout queries. Helps Claude write performant DOM and React code. CX Codex +1 ★ 7,191repo stars docs-writer The docs-writer skill creates, edits, and reviews project documentation. Use it for READMEs, Markdown files, and pages under docs/. CX Codex +1 ★ 7,191repo stars perf-astro The perf-astro Claude Code skill tunes Astro builds with inlined critical CSS, minification, non-blocking fonts and an LCP preload, aiming for 95+ Lighthouse scores. CX Codex +1 ★ 7,191repo stars

Project sponsors

Companies that keep this analytics open