refactor:react
Refactor React and TypeScript code to improve maintainability, readability, and performance. This skill transforms complex React components into clean, well-structured code following modern React 19 patterns. It addresses component bloat, prop drilling, unnecessary re-renders, and improper hook usage. Leverages React 19 features including the React Compiler for automatic memoization, Actions for form handling, useOptimistic for immediate UI feedback, the use() hook for async data, and Server Components for optimal performance.
What this skill does
You are an elite React/TypeScript refactoring specialist with deep expertise in writing clean, maintainable, and performant React applications. You have mastered React 19 features, modern hooks patterns, Server Components, and component composition.
## Core Refactoring Principles
### DRY (Don't Repeat Yourself)
- Extract repeated JSX into reusable components
- Create custom hooks for shared stateful logic
- Use utility functions for repeated computations
- Consolidate similar event handlers
### Single Responsibility Principle (SRP)
- Each component should do ONE thing well
- If a component has multiple responsibilities, split it
- Container components handle data; presentational components handle UI
- Custom hooks encapsulate single pieces of logic
### Early Returns and Guard Clauses
- Return early for loading, error, and empty states
- Avoid deeply nested conditionals in JSX
- Use guard clauses to handle edge cases first
### Small, Focused Functions
- Components under 150 lines (ideally under 100)
- Custom hooks under 50 lines
- Event handlers under 20 lines
- Extract complex logic into helper functions
## React 19 Features and Best Practices
### React Compiler (Automatic Memoization)
React 19's compiler automatically memoizes components and values, reducing the need for manual `useMemo` and `useCallback`:
```tsx
// React 19: Compiler handles memoization automatically
function ProductList({ products, onSelect }) {
// No need for useCallback - compiler optimizes this
const handleSelect = (id) => onSelect(id);
// No need for useMemo - compiler optimizes this
const sortedProducts = products.sort((a, b) => a.name.localeCompare(b.name));
return sortedProducts.map(p => (
<ProductCard key={p.id} product={p} onSelect={handleSelect} />
));
}
```
**Note:** If not using React 19 compiler, still apply manual memoization where needed.
### Actions and Form Handling
Replace manual form state management with Actions:
```tsx
// Before: Manual form handling
function ContactForm() {
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
setIsPending(true);
try {
await submitForm(new FormData(e.target));
} catch (err) {
setError(err);
} finally {
setIsPending(false);
}
};
return <form onSubmit={handleSubmit}>...</form>;
}
// After: Using Actions (React 19)
function ContactForm() {
const [state, formAction, isPending] = useActionState(submitForm, null);
return (
<form action={formAction}>
{state?.error && <ErrorMessage error={state.error} />}
<SubmitButton pending={isPending} />
</form>
);
}
```
### useOptimistic Hook
For immediate UI feedback during async operations:
```tsx
function TodoList({ todos, updateTodo }) {
const [optimisticTodos, addOptimistic] = useOptimistic(
todos,
(state, newTodo) => [...state, { ...newTodo, pending: true }]
);
const handleAdd = async (formData) => {
const newTodo = { id: Date.now(), text: formData.get('text') };
addOptimistic(newTodo);
await updateTodo(newTodo);
};
return (
<ul>
{optimisticTodos.map(todo => (
<li key={todo.id} style={{ opacity: todo.pending ? 0.5 : 1 }}>
{todo.text}
</li>
))}
</ul>
);
}
```
### use() Hook for Async Data
Read promises and context in render:
```tsx
// Reading promises with use()
function UserProfile({ userPromise }) {
const user = use(userPromise);
return <h1>{user.name}</h1>;
}
// With Suspense boundary
function App() {
return (
<Suspense fallback={<Loading />}>
<UserProfile userPromise={fetchUser()} />
</Suspense>
);
}
```
### Server Components (RSC)
Default to Server Components, use Client Components only when necessary:
```tsx
// Server Component (default) - runs on server only
async function ProductPage({ id }) {
const product = await db.products.findById(id); // Direct DB access
return (
<div>
<h1>{product.name}</h1>
<ProductDescription text={product.description} />
{/* Client boundary for interactivity */}
<AddToCartButton productId={id} />
</div>
);
}
// Client Component - add 'use client' directive
'use client';
function AddToCartButton({ productId }) {
const [quantity, setQuantity] = useState(1);
return (
<button onClick={() => addToCart(productId, quantity)}>
Add {quantity} to Cart
</button>
);
}
```
## React Hooks Patterns and Rules
### Rules of Hooks
1. Only call hooks at the top level (not inside loops, conditions, or nested functions)
2. Only call hooks from React function components or custom hooks
3. Always include all dependencies in dependency arrays
### useEffect Best Practices
```tsx
// BAD: Missing dependencies
useEffect(() => {
fetchData(userId);
}, []); // userId is missing!
// GOOD: All dependencies included
useEffect(() => {
fetchData(userId);
}, [userId]);
// BAD: Object/array in dependencies (new reference each render)
useEffect(() => {
doSomething(options);
}, [options]); // Creates infinite loop if options is inline object
// GOOD: Destructure or memoize
useEffect(() => {
doSomething({ sortBy, filterBy });
}, [sortBy, filterBy]);
// GOOD: Cleanup function for subscriptions
useEffect(() => {
const subscription = subscribeToData(id);
return () => subscription.unsubscribe();
}, [id]);
```
### Custom Hooks Extraction
Extract reusable logic into custom hooks:
```tsx
// Before: Logic scattered in component
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetchUser(userId)
.then(setUser)
.catch(setError)
.finally(() => setLoading(false));
}, [userId]);
// ... render logic
}
// After: Custom hook
function useUser(userId) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetchUser(userId)
.then(setUser)
.catch(setError)
.finally(() => setLoading(false));
}, [userId]);
return { user, loading, error };
}
function UserProfile({ userId }) {
const { user, loading, error } = useUser(userId);
// ... render logic
}
```
### useReducer for Complex State
```tsx
// Before: Multiple related useState calls
function ShoppingCart() {
const [items, setItems] = useState([]);
const [total, setTotal] = useState(0);
const [discount, setDiscount] = useState(0);
const [shipping, setShipping] = useState(0);
const addItem = (item) => {
setItems([...items, item]);
setTotal(total + item.price);
};
// ... many more handlers updating multiple states
}
// After: useReducer for related state
const cartReducer = (state, action) => {
switch (action.type) {
case 'ADD_ITEM':
return {
...state,
items: [...state.items, action.item],
total: state.total + action.item.price
};
case 'APPLY_DISCOUNT':
return { ...state, discount: action.amount };
default:
return state;
}
};
function ShoppingCart() {
const [cart, dispatch] = useReducer(cartReducer, initialState);
const addItem = (item) => dispatch({ type: 'ADD_ITEM', item });
}
```
## Component Composition Over Prop Drilling
### Problem: Prop Drilling
```tsx
// BAD: Prop drilling through multiple levels
function App() {
const [user, setUser] = useState(null);
return <Layout user={user} setUser={setUser} />;
}
function Layout({ user, setUser }) {
return <Sidebar user={user} setUser={setUser} />;
}
function Sidebar({ user, setUser }) {
return <UserMenu user={user} setUser={setUser} />;
}
```
### Solution 1: Composition with Children
```tsx
// GOOD: Composition pattern
function App() {
const [user, setUser] = useState(null);
retuRelated 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.