react-effects
React useEffect anti-pattern detection and correction guide. Use this skill whenever writing, reviewing, or modifying any React component that contains useEffect, or when about to add a useEffect hook. Also trigger when you see patterns like "setState inside useEffect", "effect chains", "derived state in effect", or "notify parent in effect". Covers 12 specific scenarios where Effects are unnecessary or misused, with correct alternatives. Even if the useEffect looks reasonable at first glance, consult this skill to verify it's truly needed.
What this skill does
# React Effects: When You Do and Don't Need Them
Effects are an escape hatch to synchronize React components with **external systems** (browser APIs, network, third-party libraries). Most component logic does not need Effects. Before writing or keeping a `useEffect`, run through the scenarios below — there's likely a simpler, more performant alternative.
## The Two Questions
Before every `useEffect`, ask:
1. **Is this transforming data for rendering?** If yes, compute it during render instead.
2. **Is this handling a user event?** If yes, put it in an event handler instead.
If neither applies, you might actually need an Effect.
---
## Scenarios Where Effects Are Wrong
### 1. Derived State from Props or State
The most common mistake. If a value can be calculated from existing props or state, it's not state at all — it's a render-time computation.
**Why the Effect is harmful:** React renders once with stale values, commits to DOM, then the Effect fires a second setState triggering another full render cycle. The user briefly sees outdated UI.
```tsx
// WRONG: Redundant state + unnecessary Effect
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
// RIGHT: Compute during render — zero extra renders, zero extra state
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const fullName = firstName + ' ' + lastName;
```
**Detection pattern:** `useEffect` whose only job is calling `setSomeState(f(props, state))`.
### 2. Caching Expensive Computations
When the computation is genuinely expensive (>1ms in production profiling), use `useMemo` — not an Effect with state.
```tsx
// WRONG: Effect + state for caching
const [visibleTodos, setVisibleTodos] = useState([]);
useEffect(() => {
setVisibleTodos(getFilteredTodos(todos, filter));
}, [todos, filter]);
// RIGHT (simple case): Just compute it
const visibleTodos = getFilteredTodos(todos, filter);
// RIGHT (expensive): useMemo skips recomputation when deps haven't changed
const visibleTodos = useMemo(
() => getFilteredTodos(todos, filter),
[todos, filter]
);
```
**When is it expensive?** Use `console.time`/`console.timeEnd` in production mode. If the logged time is consistently >=1ms, memoize. Dev mode timings are unreliable due to extra checks.
### 3. Resetting All State When a Prop Changes
When a prop like `userId` changes and you want to clear all component state (form fields, scroll position, etc.), don't reset each piece of state in an Effect — use React's `key` mechanism.
**Why the Effect is harmful:** The component renders once with stale state (old comment shown for new user), then the Effect clears it, causing a second render. Every nested component with state needs its own reset Effect — fragile and error-prone.
```tsx
// WRONG: Effect to reset state on prop change
function ProfilePage({ userId }) {
const [comment, setComment] = useState('');
useEffect(() => {
setComment('');
}, [userId]);
return /* ... */;
}
// RIGHT: key tells React "this is a different component instance"
function ProfilePage({ userId }) {
return <Profile userId={userId} key={userId} />;
}
function Profile({ userId }) {
const [comment, setComment] = useState(''); // Auto-resets when key changes
return /* ... */;
}
```
**Detection pattern:** `useEffect(() => { setX(initial); setY(initial); ... }, [someProp])` resetting multiple states.
### 4. Adjusting Some State When a Prop Changes
Sometimes you don't want to reset *all* state — just adjust one piece. The best approach is often to avoid the state entirely and derive the value.
```tsx
// WRONG: Effect to clear selection when items change
function List({ items }) {
const [selection, setSelection] = useState(null);
useEffect(() => {
setSelection(null);
}, [items]);
return /* ... */;
}
// BETTER: Store the ID, derive the selected object
function List({ items }) {
const [selectedId, setSelectedId] = useState(null);
// If the selected item is still in the list, keep it; otherwise null
const selection = items.find(item => item.id === selectedId) ?? null;
return /* ... */;
}
```
If you truly must adjust state during render (rare), you can do so without an Effect, but this pattern should be a last resort:
```tsx
function List({ items }) {
const [prevItems, setPrevItems] = useState(items);
const [selection, setSelection] = useState(null);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null);
}
}
```
### 5. Event-Specific Logic in Effects
If code should run **because the user did something** (clicked a button, submitted a form), it belongs in an event handler — not an Effect that reacts to state changes.
**Why the Effect is harmful:** The logic runs whenever the tracked state changes, including on page load, navigation, or other state restorations — not just in response to the user action.
```tsx
// WRONG: Shows notification whenever product.isInCart becomes true
// (including page refresh, back navigation, etc.)
function ProductPage({ product, addToCart }) {
useEffect(() => {
if (product.isInCart) {
showNotification(`Added ${product.name} to cart!`);
}
}, [product]);
function handleBuyClick() {
addToCart(product);
}
}
// RIGHT: Notification is a direct response to user action
function ProductPage({ product, addToCart }) {
function buyProduct() {
addToCart(product);
showNotification(`Added ${product.name} to cart!`);
}
function handleBuyClick() {
buyProduct();
}
function handleCheckoutClick() {
buyProduct();
navigateTo('/checkout');
}
}
```
**Detection pattern:** `useEffect` that runs `showNotification`, `navigate`, `alert`, or other side effects triggered by `[someFlag]` that was set in an event handler.
### 6. POST Requests Triggered by User Actions
Sending data to a server in response to a user action (form submit, button click) belongs in the event handler. Only truly display-driven requests (like analytics page views) belong in Effects.
```tsx
// WRONG: Roundabout way to send form data
const [jsonToSubmit, setJsonToSubmit] = useState(null);
useEffect(() => {
if (jsonToSubmit !== null) {
post('/api/register', jsonToSubmit);
}
}, [jsonToSubmit]);
function handleSubmit(e) {
e.preventDefault();
setJsonToSubmit({ firstName, lastName });
}
// RIGHT: Submit directly in the event handler
function handleSubmit(e) {
e.preventDefault();
post('/api/register', { firstName, lastName });
}
// This analytics Effect IS correct — it runs because the component displayed
useEffect(() => {
post('/analytics/event', { eventName: 'visit_form' });
}, []);
```
### 7. Chains of Effects
Multiple Effects where each one sets state that triggers the next Effect. This creates a cascade of unnecessary renders and makes the logic hard to follow.
**Why the Effect chain is harmful:** Each setState in the chain triggers a separate render pass. If there are 4 Effects in the chain, the component renders 5 times instead of once. The logic is scattered across multiple Effects making it hard to trace.
```tsx
// WRONG: Chain of Effects triggering each other
useEffect(() => {
if (card !== null && card.gold) {
setGoldCardCount(c => c + 1);
}
}, [card]);
useEffect(() => {
if (goldCardCount > 3) {
setRound(r => r + 1);
setGoldCardCount(0);
}
}, [goldCardCount]);
useEffect(() => {
if (round > 5) {
setIsGameOver(true);
}
}, [round]);
// RIGHT: Derive what you can, compute the rest in the event handler
const isGameOver = round > 5; // Derived, not state
function handlePlaceCard(nextCard) {
if (isGameOver) throw Error('Game already ended.');
setCard(nextCard);
if (nextCard.gold) {
if (goldCardCount < 3) {
setGoldCardCount(goldCardCount + 1);
} else {
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.