Chapter 3: Cleaning Up Spaghetti Code: Let AI Refactor and Split Your React Components

During Vibe Coding, we often rush to add new features by cramming everything into the same file. Gradually, your page.tsx might bloat to 800 or even 1500+ lines. At this point, AI starts becoming less effective, and changes to one part might break another.

This messy, entangled code is called "Spaghetti Code." This chapter will teach you how to instruct AI to safely perform "code refactoring" and "component splitting."

Why Do Large Files Make AI Dumber?

  1. Wasted Context Window: Every conversation requires AI to read the entire file. A 1500-line file consumes a massive amount of tokens, causing AI to "forget" your original requirements.
  2. High Modification Risk: When a single file contains the Header, Sidebar, Main Content, and Footer, asking AI to modify the Footer might accidentally alter the Header's state.
  3. Unreadable for Humans: Vibe Coding doesn’t mean humans shouldn’t read the code. When files grow beyond your grasp, you lose control of the project.

The Golden Rule of Refactoring: Single Responsibility Principle (SRP)

Before asking AI to split components, you must internalize the concept of "single responsibility."
A React component should only do one thing.

For example, a PricingPage shouldn’t handle:

  • Fetching pricing plans from the database
  • Rendering the UI for plan cards
  • Processing Stripe API logic for checkout buttons
  • Rendering FAQ accordions

Instead, it should be split into:

  • PricingPage (only for composition)
    • PricingCard (only for rendering card UI)
    • CheckoutButton (only for payment logic)
    • FaqSection (only for FAQ logic)

Hands-On: How to Craft the "Split Components" Prompt

Don’t just tell AI: "Make this file smaller." That’s too vague, and AI might produce a bizarre structure.

Use this refactoring-specific prompt template:

[Task Objective]
The current src/app/pricing/page.tsx file is too long. I want to refactor and split components to improve maintainability.

[Splitting Plan]
Split the code into these three files:

  1. src/components/pricing/PricingCard.tsx: Renders the UI for a single pricing card. Accepts tier (plan data) as props.
  2. src/components/pricing/FaqSection.tsx: Renders the FAQ section at the bottom, including accordion toggle state (useState).
  3. src/app/pricing/page.tsx: Remains the main page, importing the above components and retaining data-fetching logic.

[Execution Requirements]

  1. Proceed step by step. First, provide the complete code for PricingCard.tsx.
  2. Ensure TypeScript Interfaces/Types are correctly exported and shared.
  3. Preserve all Tailwind styles and animations exactly as they were.

Pitfalls to Avoid During Splitting

When AI provides the split code, watch for these issues:

1. Prop Drilling

After splitting, variables like const [isLoading, setIsLoading] = useState(false) in the main file won’t be accessible in child components. AI should pass these via props. If it misses any, remind it: "Remember to pass isLoading as a prop to PricingCard."

2. Absolute vs. Relative Paths

After moving files to src/components/, import paths might break. Check AI’s imports:
import { AlertCircle } from "lucide-react";
import { cn } from "@/lib/utils";
import { cn } from "../../lib/utils"; (In Next.js, prefer @/ absolute paths)

3. Do One Thing at a Time

Critical Rule: Never mix "refactoring" with "adding features"!
If you want to split a button and add a loading spinner, do it in two steps:
Step 1: Split. Test if it works.
Step 2: Add the spinner.
This ensures you can always git commit back to a safe point.

Benefits of Regular Cleanups

Make it a habit to ask AI for a "component split" when a file exceeds 300 lines. You’ll notice:

  • AI writes code faster (fewer tokens consumed).
  • Fewer bugs (state is isolated in individual components).
  • Your own coding experience improves.

This is the ultimate secret to sustainable Vibe Coding for large-scale commercial projects!

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Advanced Prompt Patterns

Iterative Refinement

Instead of one massive prompt, break work into steps.

Step 1: "Create a TypeScript interface for a User with id, name, email, role"
Step 2: "Now create a React component that displays a user card from this interface"
Step 3: "Add edit and delete buttons to the card"
Step 4: "Now connect it to a mock API with loading and error states"

Few-Shot Prompting

Give examples of what you want before asking.

Example 1:
Input: "user123"
Output: "USR-123"

Example 2:
Input: "order456"
Output: "ORD-456"

Now convert: "product789"
→

Chain-of-Thought

Ask AI to reason step by step.

"I need to calculate the total price with tax and shipping.
 Think step by step:
 1. Calculate subtotal (price × quantity)
 2. Add tax (subtotal × 0.08)
 3. Add shipping ($5.99 if subtotal < $50, else free)
 4. Return total

 Items: [{price: 25, qty: 2}, {price: 10, qty: 1}]"

Building Complex Features

Full Feature Prompt

Create a searchable product list with the following:

Data:
- Products array with: id, name, price, category, imageUrl
- 15+ sample products across 3 categories

Requirements:
- Search bar filters by name in real-time
- Category dropdown filter
- Sort by price (low/high)
- Grid layout with product cards
- Loading skeleton animation
- Empty state when no results
- Responsive design (2 cols mobile, 4 cols desktop)

Tech:
- React + TypeScript
- No external UI library
- Tailwind CSS for styling

Component Composition

// AI-generated: Compound component pattern
interface ProductListProps {
  products: Product[];
  onProductClick: (product: Product) => void;
}

ProductList.Search = ProductSearch;
ProductList.Filter = CategoryFilter;
ProductList.Sort = SortSelect;
ProductList.Grid = ProductGrid;
ProductList.Card = ProductCard;

// Usage:
<ProductList products={data}>
  <ProductList.Search />
  <ProductList.Filter />
  <div className="flex gap-4">
    <ProductList.Sort />
  </div>
  <ProductList.Grid />
</ProductList>

Code Review with AI

Review Prompt

Review this React component for:
1. Bugs and logic errors
2. Performance issues
3. Accessibility problems
4. Security vulnerabilities
5. Code style and best practices

[paste component code]

AI Review Checklist

| Category | What AI Checks | |----------|---------------| | Correctness | Logic errors, wrong conditions, missing edge cases | | Performance | Unnecessary re-renders, large lists without virtualization | | Accessibility | Missing aria labels, keyboard navigation, contrast | | Security | XSS vulnerabilities, unvalidated inputs, exposed secrets | | Maintainability | Duplicate code, unclear naming, missing types |

Summary

Advanced AI coding patterns include iterative refinement, few-shot prompting, chain-of-thought reasoning, and AI-assisted code review. These techniques produce higher quality, more reliable code.

Key takeaways:

  • Iterative refinement: multiple small prompts beat one huge prompt |
  • Few-shot prompting: give examples before asking |
  • Chain-of-thought: ask AI to reason step by step |
  • Compound components enable flexible, composable UIs |
  • AI code review checks correctness, performance, accessibility, security |
  • Always review AI outputs — AI can make mistakes |
  • Break complex features into clear, structured requirements |
  • Use TypeScript types to guide AI code generation |

What's Next: Testing with AI

The next chapter covers AI-assisted testing.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!