# Refactor View

> Extract and refactor SwiftUI views for better organization and reusability. Use when views become too large or need restructuring.

- Skill: `duboc/refactor-view` (Agent Skill)
- Install (CLI): `npx skillmds@latest add duboc/refactor-view`
- Raw SKILL.md: https://api.skillmd.com/api/skills/duboc/refactor-view/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: duboc (https://skillmd.com/u/duboc)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/duboc/refactor-view

---


# Refactor SwiftUI View

Extract and refactor SwiftUI views for better maintainability.

## When to Refactor

- View exceeds 100 lines
- Deeply nested view hierarchy
- Repeated view patterns
- Complex conditional logic in body
- Performance issues from large views

## Workflow

### 1. Analyze Current View
- Read the source file
- Identify logical sections
- Find repeated patterns
- Note dependencies and state

### 2. Plan Extraction

#### Extract Subviews For:
- Distinct UI sections (header, content, footer)
- Repeated patterns (list rows, cards)
- Complex conditional views
- Reusable components

#### Keep Together:
- Tightly coupled logic
- Shared state that's complex to pass
- Animation coordination

### 3. Refactoring Patterns

#### Extract as Computed Property
```swift
// Before
var body: some View {
    VStack {
        // 50 lines of header code
        // 50 lines of content code
    }
}

// After
var body: some View {
    VStack {
        headerView
        contentView
    }
}

@ViewBuilder
private var headerView: some View {
    // Header code
}

@ViewBuilder
private var contentView: some View {
    // Content code
}
```

#### Extract as Separate Struct
```swift
// For reusable components
struct ItemRow: View {
    let item: Item

    var body: some View {
        HStack {
            // Row content
        }
    }
}
```

#### Extract View Modifier
```swift
// Before: repeated styling
Text("Title")
    .font(.headline)
    .foregroundStyle(.primary)
    .padding()

// After: custom modifier
Text("Title")
    .titleStyle()

extension View {
    func titleStyle() -> some View {
        self
            .font(.headline)
            .foregroundStyle(.primary)
            .padding()
    }
}
```

### 4. Verify Refactoring
- Build succeeds
- Previews work
- Behavior unchanged
- Tests still pass

## Best Practices

- Pass only needed data to subviews
- Use @Binding for two-way data flow
- Prefer composition over deep nesting
- Keep related views in same file initially
- Extract to separate files when reused
- Add previews for extracted components

