Context Engineering with Claude Code: Stop Rewriting AI-Generated Code
You fire up Claude Code and ask it to “create a user profile component.” It scans your project, picks up some patterns, and generates something… but it’s using a state management approach you abandoned months ago. The TypeScript types are generic. The styling is inconsistent with your design system. It’s technically correct, but it doesn’t fit your codebase.
Sound familiar? Claude Code is incredibly capable, but without proper context engineering, it’s like hiring a talented developer who has never seen your codebase. They’ll write good code, but not your team’s code.
This is where context engineering comes in. It’s the difference between getting code that “mostly works” and getting code that’s production-ready from the first iteration.
Here’s what actually happens when you use Claude Code without context engineering:
The solution isn’t just better prompts - it’s systematic context engineering using the R&D Framework.
There are only two ways to improve how Claude Code understands your project:
| Strategy | What It Means | When to Use |
|---|---|---|
| 🔥 REDUCE | Minimize unnecessary information in context | When Claude is unfocused, slow, or giving generic responses |
| 🎯 DELEGATE | Split complex work across multiple focused sessions | When tasks are complex or require different expertise areas |
Every technique in this guide fits into one of these categories. Master this framework, and you’ll get production-ready code from Claude Code on the first try.
Problem: Claude Code auto-loads every MCP server in your config, filling your context with tools you’re not using.
Solution: Only add MCP servers when you actually need them.
# Check what's currently loaded
claude mcp list
# Remove unnecessary MCPs
claude mcp remove puppeteer
claude mcp remove sqlite
# Add specific MCPs only when needed
# Example: Add Playwright for browser testing
claude mcp add playwright npx @playwright/mcp@latest
# Example: Add Context7 for getting latest documentation on libs/frameworks
claude mcp add context7 -- npx -y @upstash/context7-mcpImpact: Cleaner context window means faster responses and more focused suggestions. Can save 10,000+ tokens per session.
Problem: Your CLAUDE.md file grows huge with every project detail, consuming precious context space.
Solution: Replace static memory with dynamic context priming using custom slash commands.
Create focused commands in .claude/commands/:
<!-- .claude/commands/react-patterns.md -->
You are a senior React/TypeScript developer writing production-ready code.
## Our Stack
- React 18 with TypeScript strict mode
- Tailwind CSS (utilities only, never custom CSS)
- Next.js 14 for routing and SSR
- Supabase for backend and auth
- Convex for real-time data
## Non-Negotiable Patterns
- Extract ALL business logic to custom hooks
- Components max 50 lines - compose smaller parts
- TypeScript interfaces for all props (no 'any' types)
- Tailwind utilities only - zero custom CSS
- Always include loading and error states
## File Structure
src/
├── components/ # UI only, no business logic
├── hooks/ # All business logic here
├── types/ # TypeScript interfaces
└── pages/ # Next.js pages
## Example of Our Pattern
// âś… Correct: Clean component with extracted logic
interface UserProfileProps {
userId: string;
}
function UserProfile({ userId }: UserProfileProps) {
const { user, loading, error } = useUser(userId);
if (loading) return <ProfileSkeleton />;
if (error) return <ErrorBoundary error={error} />;
return (
<div className="p-6 border border-gray-200 rounded-lg">
<h2 className="text-xl font-semibold">{user.name}</h2>
<p className="text-gray-600">{user.email}</p>
</div>
);
}Now in Claude Code, use it like this:
claude
# Load your React patterns instantly
> /react-patterns Create a user settings component with form validationImpact: Instant context priming for any task. No bloated CLAUDE.md file.
Problem: One session trying to do everything (build features + review code + write tests) becomes unfocused.
Solution: Create specialized context commands for different types of work.
<!-- .claude/commands/review.md -->
You are a senior engineer conducting a thorough code review.
Focus exclusively on reviewing code for:
- Adherence to our React patterns (hooks extracted, <50 lines)
- TypeScript strictness (no 'any' types)
- Tailwind usage (no custom CSS)
- Error handling (loading/error states)
- Test coverage
Provide focused, actionable feedback. Be specific about what needs to change.<!-- .claude/commands/testing.md -->
You are a testing specialist using React Testing Library and Jest.
## Our Testing Standards
- Unit tests for all custom hooks
- Integration tests for user flows
- Test behavior, not implementation
- Focus on what users see and do
## Always Test
- Loading states
- Error states
- Success paths
- Edge casesUsage Pattern:
# Development work
claude
> /react-patterns Build the checkout flow
# Code review (same session or new one)
> /review @src/components/CheckoutForm.tsx
# Testing work
> /testing @src/components/CheckoutForm.tsx Write comprehensive testsImpact: Claude stays focused on one type of work at a time. Reviews are consistent. Tests follow your patterns.
Problem: Long sessions exhaust the context window. Claude forgets your requirements or starts making different choices.
Solution: Use Claude Code’s built-in memory management strategically.
# When you establish important context, save it to memory
> # This project uses Supabase auth, TypeScript strict mode, Tailwind only
> # Components max 50 lines, custom hooks for all business logic
> # We're building an e-commerce platform with real-time inventory
# When context gets full, compact strategically
> /compact Keep only the current feature work and our coding standards
# For major context shifts, clear and start fresh
> /clear
# Reference previous work through CLAUDE.md
> Check CLAUDE.md for our auth implementation. Build the user settings page following the same patterns.Pro Tips:
# shortcut to add to memory: > # Remember: All forms use react-hook-form/compact at logical breakpoints (feature complete, tests passing)/clear when switching to completely different workCLAUDE.md to bring back previous context without bloatImpact: Maintain context efficiency throughout long projects. Claude stays consistent with your patterns across sessions.
Problem: Complex research, analysis, or verification tasks flood your main context with 100K+ tokens of details, making Claude lose focus.
Solution: Use sub-agents - specialized AI assistants that work in their own separate context windows and return only summaries.
The Game-Changer: Each sub-agent gets its own 200K token context window. They can burn through massive analysis, logs, or research, and your main thread only sees the conclusion.
How Sub-Agents Work:
Create Your First Sub-Agent:
## <!-- .claude/agents/react-researcher.md -->
name: react-researcher
description: Use PROACTIVELY when researching React patterns, best practices, or implementation approaches. Research specialist who plans but never implements.
tools: read, search, bash
model: sonnet
---
You are a React research specialist who creates implementation plans.
## Your Role - CRITICAL
1. Research best practices for the requested feature
2. Analyze trade-offs and implementation approaches
3. Create detailed architectural plans with code examples
4. Save findings to docs/research/[feature]-plan.md
5. Return ONLY a 3-line summary to the main thread
## Research Process
1. Use Context7 MCP or web search for latest patterns
2. Check our codebase for existing similar implementations
3. Document pros/cons of different approaches
4. Provide specific, actionable recommendations
## Output Format
Save to docs/research/[feature]-plan.md:
# [Feature] Implementation Plan
## Recommended Approach
[Specific recommendation with reasoning]
## Implementation Steps
1. [Step with code example]
2. [Step with code example]
## Trade-offs
- Pro: [specific benefit]
- Con: [specific drawback]
## Examples
[Code examples showing the pattern]
NEVER write implementation code. Your job is to research and plan so the main agent can implement efficiently.Create a Review Sub-Agent:
## <!-- .claude/agents/code-reviewer.md -->
name: code-reviewer
description: Use PROACTIVELY for code review. Expert at identifying issues with React patterns, TypeScript, and our coding standards.
tools: read, grep, bash
model: sonnet
---
You are a senior code reviewer specializing in our tech stack.
## Review Checklist
- React patterns (hooks extracted, <50 lines, proper composition)
- TypeScript strictness (no 'any', proper interfaces)
- Tailwind usage (no custom CSS)
- Error handling (loading/error states)
- Security considerations
- Performance implications
## Review Process
1. Read all relevant files
2. Analyze against our standards
3. Check for common anti-patterns
4. Verify test coverage
5. Save detailed review to docs/reviews/[feature]-review.md
6. Return ONLY summary with severity counts
## Output Format
Save to docs/reviews/[feature]-review.md:
# Code Review: [Feature]
## Critical Issues (Must Fix)
- [Issue with file:line reference]
## Warnings (Should Fix)
- [Issue with explanation]
## Suggestions (Consider)
- [Improvement opportunity]
## Strengths
- [What was done well]
Return to main thread: "Review complete. Found X critical, Y warnings, Z suggestions. Details in docs/reviews/[feature]-review.md"Using Sub-Agents in Your Workflow:
claude
# Automatic invocation - Claude detects when to use sub-agent
> I need to implement user authentication with social login
# Claude automatically uses react-researcher sub-agent
# Sub-agent researches, saves to docs/research/auth-plan.md
# Returns: "Research complete. OAuth 2.0 recommended. Plan in docs/research/auth-plan.md"
# Manual invocation - You explicitly request a sub-agent
> Use react-researcher to analyze form validation patterns for our checkout flow
# Review with sub-agent
> Use code-reviewer to review the authentication implementation
> @src/components/LoginForm.tsx
> @src/hooks/useAuth.ts
# Sub-agent reviews, saves detailed findings
# Returns: "Review complete. Found 1 critical, 2 warnings. Details in docs/reviews/auth-review.md"
# Main agent stays clean and focused
> Read docs/research/auth-plan.md and implement OAuth login following our React patternsThe Power: Context Window Math
WITHOUT SUB-AGENTS:
Main-context: 200K tokens
├─ Research on OAuth: 45K tokens
├─ API documentation: 30K tokens
├─ Implementation work: 60K tokens
├─ Test logs: 40K tokens
└─ Code review: 25K tokens
= TOTAL: 200K (context exhausted, performance degrading)
WITH SUB-AGENTS:
Main-context: 35K tokens
├─ Research sub-agent summary: 1K tokens
├─ Implementation work: 30K tokens
└─ Review sub-agent summary: 1K tokens
= TOTAL: 35K tokens (165K saved, context stays clean)
Sub-agent contexts (isolated):
├─ Researcher burned: 80K tokens (in its own window)
└─ Reviewer burned: 65K tokens (in its own window)Creating Sub-Agents with /agents Command:
claude
# Interactive sub-agent creation
> /agents
# Choose "Create new agent"
# Claude guides you through:
# - Name and description
# - Tools needed
# - System prompt
# Or ask Claude to generate one
> Create a sub-agent for analyzing database performance issues
# Claude generates the markdown file for you to customizeManaging Sub-Agents:
# List all sub-agents
> /agents
# View sub-agent details
> Show me the react-researcher sub-agent config
# Edit a sub-agent
> /agents
# Select agent to editSub-Agent Best Practices:
Real-World Sub-Agent Workflow:
claude
# Step 1: Research (sub-agent)
> I need to add real-time chat to our app
# react-researcher sub-agent activates
# Researches Convex patterns, WebSocket alternatives, state management
# Saves detailed plan to docs/research/realtime-chat-plan.md
# Returns: "Convex subscriptions recommended. Plan ready."
# Step 2: Implement (main agent)
> /react-patterns Read docs/research/realtime-chat-plan.md
> Implement the MessageList component with real-time updates
# Main agent implements following the plan
# Context stays clean, focused on implementation
# Step 3: Review (sub-agent)
> Use code-reviewer to review the chat implementation
# Reviewer sub-agent analyzes all files
# Checks patterns, security, performance
# Saves to docs/reviews/chat-review.md
# Returns: "2 warnings found. Review saved."
# Step 4: Fix (main agent)
> Read docs/reviews/chat-review.md and fix the warnings
# Main agent reads review, makes focused fixes
# Step 5: Verify (sub-agent)
> Use code-reviewer to verify fixes
# Returns: "All issues resolved. âś…"Impact:
Symptoms: Gets file structure wrong, uses different naming, ignores your stack Root Cause: Generic training data overriding your specific context Fix: Be more explicit in your context commands
<!-- Make your patterns more specific -->
## CRITICAL - Never Deviate
- TypeScript strict mode ONLY (no JavaScript)
- Tailwind utilities ONLY (if I see custom CSS, you failed)
- Custom hooks for ALL business logic (no exceptions)
- Components max 50 lines (hard limit, no negotiation)
## File Naming Rules
- Components: PascalCase (UserProfile.tsx)
- Hooks: camelCase with 'use' prefix (useUser.ts)
- Types: PascalCase with domain suffix (UserTypes.ts)
## Stack (Don't suggest alternatives)
- Database: Supabase (not Firebase, not MongoDB)
- Styling: Tailwind (not CSS Modules, not styled-components)
- State: React Query + Zustand (not Redux, not Context)Symptoms: Starts suggesting different approaches, inconsistent with earlier work Root Cause: Context window filling up, earlier instructions getting compressed Fix: Re-prime context strategically
# Method 1: Reload your context command
> /react-patterns Remember our patterns and continue with the checkout flow
# Method 2: Add critical reminders to memory
> # Critical reminder: TypeScript strict, Tailwind only, custom hooks for logic
# Method 3: Compact at checkpoints
> /compact Preserve only: current feature work, our coding standards, decisions madeSymptoms: Long response times, generic suggestions, contradictory advice Root Cause: Context window near capacity Fix: Session management
# Check if you're near limit (look for auto-compact warnings)
# Option 1: Compact and continue
> /compact Keep current feature and coding patterns only
# Option 2: Clear and start fresh
> Save progress summary to CLAUDE.md
> /clear
> Load from CLAUDE.md and continueSymptoms: Slower responses, context bloat Root Cause: Unnecessary MCPs loaded Fix: Audit and optimize
# See what's loaded
claude mcp list
# Remove what you're not using
claude mcp remove puppeteer
claude mcp remove sqlite
# Add back only when needed
claude mcp add playwright npx @playwright/mcp@latest# Complete feature development with research and verification
claude
# Step 1: Research with sub-agent
> I need to add payment processing with Stripe
# react-researcher sub-agent activates automatically
# Researches Stripe best practices, security considerations
# Saves to docs/research/stripe-payment-plan.md
# Returns: "Research complete. Stripe Elements recommended. Plan ready."
# Step 2: Implementation with patterns
> /react-patterns Read docs/research/stripe-payment-plan.md and Implement the payment flow with Stripe Elements
# Step 3: Review with sub-agent
> Use code-reviewer to review the payment implementation
# Sub-agent reviews security, error handling, UX
# Saves to docs/reviews/payment-review.md
# Returns: "Review complete. 1 security concern, 2 warnings."
# Step 4: Fix issues
> Read docs/reviews/payment-review.md and address all issues
# Main context stays clean, focused on fixes
# Step 5: Generate tests with sub-agent
> Use test-generator to create comprehensive payment tests @src/components/PaymentForm.tsx
# Sub-agent generates tests, runs them
# Returns: "Generated 12 tests, all passing."
# Step 6: Performance check
> Use performance-analyzer to check payment flow performance
# Returns: "No bottlenecks found. Load time: 1.2s"claude
# Quick review with sub-agent
> Use code-reviewer to analyze this PR
> @src/components/Dashboard.tsx
> @src/components/DashboardStats.tsx
> @src/hooks/useDashboardData.ts
# Sub-agent reviews everything, saves detailed report
# Returns: "Review complete. 3 issues found. Details in docs/reviews/dashboard-pr-review.md"
# Main agent fixes based on review
> Read docs/reviews/dashboard-pr-review.md and fix all issues
# Verify fixes
> Use code-reviewer to verify the fixes are correct
# Returns: "All issues resolved. âś…"claude
# Performance analysis with sub-agent
> The user list page feels slow. Use performance-analyzer to investigate
# Sub-agent profiles the page, analyzes renders
# Saves to docs/performance/user-list-analysis.md
# Returns: "Found 2 bottlenecks: unnecessary re-renders, unoptimized queries"
# Read analysis and implement fixes
> /react-patterns Read docs/performance/user-list-analysis.md and Implement the recommended optimizations
# Verify improvements
> Use performance-analyzer to measure improvements
# Returns: "Performance improved 3x. Load time: 0.4s (was 1.2s)"claude
# Analysis
> Analyze this legacy component for modernization opportunities @src/legacy/OldDashboard.js
# Add findings to memory
> # Legacy: Class components, inline styles, prop drilling
> # Plan: Function components, Tailwind, custom hooks
> # Constraint: Keep same props interface
# Research modern patterns with sub-agent
> Use react-researcher to research the best patterns for this refactor
# Sub-agent researches, saves plan
# Returns: "Modernization plan ready in docs/research/dashboard-refactor-plan.md"
# Implement refactor
> /react-patterns Read docs/research/dashboard-refactor-plan.md and Refactor OldDashboard using our modern patterns. Maintain the same props interface for backward compatibility
# Review the refactor
> Use code-reviewer to ensure the refactor follows our patterns
# Returns: "Refactor looks good. All patterns followed. âś…"claude
# Research phase
> I need to build a real-time collaborative document editor
# react-researcher sub-agent activates
# Researches: WebSocket vs Convex, CRDT libraries, conflict resolution
# Saves comprehensive plan
# Returns: "Recommend Convex + Yjs. Full plan in docs/research/collab-editor-plan.md"
# Implementation phase
> /react-patterns Read docs/research/collab-editor-plan.md and Implement the DocumentEditor component with real-time collaboration
# Testing phase
> Use test-generator to create tests for collaborative editing @src/components/DocumentEditor.tsx
# Returns: "Generated 15 tests including concurrent editing scenarios"
# Performance check
> Use performance-analyzer to check performance with 10 concurrent users
# Returns: "Performance excellent. Latency <50ms for 10 users"
# Security review
> Use code-reviewer to review for security issues in collaborative features
# Returns: "1 critical: Need rate limiting. 2 warnings about data validation"
# Fix security issues
> Fix the security issues found in the review
# Final verification
> Use code-reviewer to verify all security issues are resolved
# Returns: "All security issues resolved. Ready for production. âś…"Track these metrics to see if your context engineering is working:
| Metric | Before Context Engineering | After (Commands + Sub-Agents) |
|---|---|---|
| Code Quality | 40% needs major edits | 90% production-ready first try |
| Pattern Consistency | Inconsistent across sessions | Follows patterns reliably |
| Development Speed | 3-4 iterations to get it right | 1 iteration with sub-agent verification |
| Context Window Usage | Constant resets, context exhausted | Clean main context, work in sub-agents |
| Code Review Time | 30+ minutes manual review | * 2 minutes with review sub-agent |
| Bug Detection | Found in production | Caught by review sub-agent pre-merge |
| Token Efficiency | 200K tokens for complex features | 40K main + isolated sub-agent work |
* Note: Always do a final review, this will also help you to get a better understanding of the code and re-align if needed.
.claude/commands/react-patterns.md> /react-patterns [task]/review for consistent code reviews/testing when you start writing testscode-reviewer for automated reviewsreact-researcher sub-agent for complex featuresStart with these three sub-agents:
Add these as you get better:
# Context commands AND sub-agents are version controlled
.claude/
├── commands/ # Commit to git
│ ├── react-patterns.md
│ ├── review.md
│ └── testing.md
└── agents/ # Commit to git
├── react-researcher.md
├── code-reviewer.md
└── test-generator.md
# Everyone on the team gets the same context
git clone your-repo
claude
> /react-patterns # Same patterns for all devs
> Use code-reviewer to review my code # Same review standardsMost developers use Claude Code and get okay results. Advanced developers use context engineering and get almost perfect results with minimal iterations.
The difference? Systematic context engineering using the R&D framework:
The 5-level progression:
Master this, and you’ll transform Claude Code from a helpful assistant into a focused coding team that understands your codebase as well as your senior developers do.
The question isn’t whether AI will change development - it’s whether you’ll master context engineering before your competition does.
Ready to level up further? Check out my MCP setup guide to build even more powerful workflows with Claude Code.