debug:react
Debug React issues systematically. Use when encountering component errors like "Cannot read property of undefined", infinite re-render loops with "Too many re-renders", stale closures in hooks, key prop warnings, memory leaks with useEffect, hydration mismatches in SSR/SSG applications, hook rule violations, missing dependency warnings, or performance bottlenecks. Covers functional components, hooks, and modern React 18/19 patterns including Server Components and concurrent features.
What this skill does
# React Debugging Guide
A systematic approach to debugging React applications, covering common error patterns, modern debugging tools, and step-by-step resolution strategies.
## Common Error Patterns
### 1. "Cannot read property of undefined" / "TypeError: X is undefined"
**Cause:** Accessing properties on null/undefined values, often from:
- Uninitialized state
- API data not yet loaded
- Incorrect prop drilling
**Solutions:**
```jsx
// Problem: Accessing nested property before data loads
const name = user.profile.name; // Error if user is undefined
// Solution 1: Optional chaining
const name = user?.profile?.name;
// Solution 2: Default values
const name = user?.profile?.name ?? 'Unknown';
// Solution 3: Early return pattern
if (!user) return <LoadingSpinner />;
return <div>{user.profile.name}</div>;
// Solution 4: Initialize state properly
const [user, setUser] = useState({ profile: { name: '' } });
```
### 2. Infinite Re-render Loops ("Too many re-renders")
**Cause:** State updates triggering renders that trigger more state updates.
**Common Triggers:**
- Calling setState directly in render
- useEffect with missing/incorrect dependencies
- Object/array references changing every render
**Solutions:**
```jsx
// Problem: setState in render
function BadComponent() {
const [count, setCount] = useState(0);
setCount(count + 1); // Infinite loop!
return <div>{count}</div>;
}
// Solution: Move to useEffect or event handler
function GoodComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(c => c + 1);
}, []); // Run once on mount
return <div>{count}</div>;
}
// Problem: Object dependency causing infinite loop
useEffect(() => {
fetchData(options);
}, [options]); // New object reference every render!
// Solution: useMemo for stable reference
const memoizedOptions = useMemo(() => ({ page: 1 }), []);
useEffect(() => {
fetchData(memoizedOptions);
}, [memoizedOptions]);
```
### 3. Stale Closure in Hooks
**Cause:** Callbacks capture old values from previous renders.
**Solutions:**
```jsx
// Problem: Stale closure in interval
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
console.log(count); // Always logs initial value!
setCount(count + 1); // Only increments once
}, 1000);
return () => clearInterval(id);
}, []); // Empty deps = stale closure
}
// Solution 1: Functional update
setCount(prevCount => prevCount + 1);
// Solution 2: useRef for mutable values
const countRef = useRef(count);
useEffect(() => {
countRef.current = count;
}, [count]);
// Solution 3: Include dependency (if appropriate)
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, [count]); // Re-creates interval on each count change
// Solution 4: useEffectEvent (React 19.2+)
const onTick = useEffectEvent(() => {
setCount(count + 1); // Always has fresh count
});
useEffect(() => {
const id = setInterval(onTick, 1000);
return () => clearInterval(id);
}, []);
```
### 4. Key Prop Warnings
**Cause:** Missing or non-unique keys in lists.
**Solutions:**
```jsx
// Problem: No key
{items.map(item => <Item data={item} />)}
// Problem: Index as key (causes issues with reordering)
{items.map((item, index) => <Item key={index} data={item} />)}
// Solution: Stable unique identifier
{items.map(item => <Item key={item.id} data={item} />)}
// For items without IDs, generate stable keys
{items.map(item => <Item key={`${item.name}-${item.date}`} data={item} />)}
```
### 5. Memory Leaks with useEffect
**Cause:** Subscriptions, timers, or async operations not cleaned up.
**Solutions:**
```jsx
// Problem: No cleanup
useEffect(() => {
const subscription = dataSource.subscribe(handleChange);
// Memory leak when component unmounts!
}, []);
// Solution: Return cleanup function
useEffect(() => {
const subscription = dataSource.subscribe(handleChange);
return () => subscription.unsubscribe();
}, []);
// Problem: Async operation after unmount
useEffect(() => {
fetchData().then(data => {
setData(data); // Error if unmounted!
});
}, []);
// Solution: AbortController for fetch
useEffect(() => {
const controller = new AbortController();
fetchData({ signal: controller.signal })
.then(data => setData(data))
.catch(err => {
if (err.name !== 'AbortError') throw err;
});
return () => controller.abort();
}, []);
// Solution: Ignore flag for other async
useEffect(() => {
let ignore = false;
fetchData().then(data => {
if (!ignore) setData(data);
});
return () => { ignore = true; };
}, []);
```
### 6. Hydration Mismatches (SSR/SSG)
**Cause:** Server-rendered HTML differs from client-side React.
**Common Triggers:**
- Using `Date.now()`, `Math.random()` in render
- Browser-only APIs (window, localStorage)
- Conditional rendering based on client state
**Solutions:**
```jsx
// Problem: Random value differs server vs client
function BadComponent() {
return <div>{Math.random()}</div>; // Hydration mismatch!
}
// Solution 1: useEffect for client-only values
function GoodComponent() {
const [randomValue, setRandomValue] = useState(null);
useEffect(() => {
setRandomValue(Math.random());
}, []);
return <div>{randomValue}</div>;
}
// Solution 2: suppressHydrationWarning (use sparingly)
<time suppressHydrationWarning>{new Date().toISOString()}</time>
// Solution 3: Client-only component
const ClientOnlyComponent = dynamic(
() => import('./ClientComponent'),
{ ssr: false }
);
```
### 7. Hook Rules Violations
**Error:** "React Hook useXXX is called conditionally"
**Cause:** Hooks called inside conditions, loops, or after early returns.
**Solutions:**
```jsx
// Problem: Conditional hook
function BadComponent({ shouldFetch }) {
if (shouldFetch) {
useEffect(() => fetchData(), []); // Error!
}
}
// Solution: Condition inside hook
function GoodComponent({ shouldFetch }) {
useEffect(() => {
if (shouldFetch) fetchData();
}, [shouldFetch]);
}
// Problem: Hook after early return
function BadComponent({ data }) {
if (!data) return null;
const [state, setState] = useState(data); // Error!
}
// Solution: Move hooks before returns
function GoodComponent({ data }) {
const [state, setState] = useState(data);
if (!data) return null;
return <div>{state}</div>;
}
```
### 8. Missing Dependencies Warning
**Error:** "React Hook has a missing dependency: 'XXX'"
**Solutions:**
```jsx
// Problem: Missing dependency
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, []); // Warning: missing 'count'
// Solution 1: Add the dependency
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
// Solution 2: Remove if truly not needed (rare)
// eslint-disable-next-line react-hooks/exhaustive-deps
// Solution 3: useCallback for function dependencies
const handleClick = useCallback(() => {
console.log(count);
}, [count]);
useEffect(() => {
element.addEventListener('click', handleClick);
return () => element.removeEventListener('click', handleClick);
}, [handleClick]);
```
## Debugging Tools
### React Developer Tools
The official browser extension for debugging React applications.
**Installation:**
- Chrome: [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools)
- Firefox: [React Developer Tools](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/)
**Key Features:**
```
Components Tab:
- Inspect component tree hierarchy
- View and edit props in real-time
- View and modify state
- Search components by name
- View component source location
Profiler Tab:
- Record render performance
- Identify slow components
- View render timing flamegraph
- Detect unnecessary re-renders
```
**Pro Tips:**
```jsx
// Name components for easier debugging
const MyComponent = () => <div />;
MyComponent.displayName = 'MyCRelated 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.