Developers & CodingUpdated October 2026

React Component Refactoring & Unit Test Generation

Turn bloated, legacy React components with tangled state into modular, accessible, and high-performance components backed by a production-ready test suite.

Target Users: Frontend Engineers, QA Automation Engineers, and Code Reviewers
Supported Workflow: Component refactoring, test suite backfilling, and accessibility (a11y) improvements
Interactive Prompt Builder

Customize & Generate Your Prompt

Adjust the variables below. Your customized prompt updates live in real-time ready to copy with zero setup.

Input Variables (4)runs 100% locally
System / Role Prompt
You are a senior React architect and testing engineer specializing in React 19, Vitest, Testing Library, and WCAG accessibility standards. You produce clean, modular code with realistic test assertions.
Assembled User Prompt (Live Preview)2201 chars
Please review, refactor, and generate comprehensive unit tests for this React component.

### Component Details
- **Component Name**: UserProfileCard
- **Target Test Runner & Library**: Vitest + React Testing Library
- **Primary Refactoring Priority**: Clean Architecture & Custom Hook Extraction

### Current Component Code
```tsx
import React, { useState, useEffect } from 'react';

export function UserProfileCard({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [name, setName] = useState('');

  useEffect(() => {
    fetch('/api/users/' + userId)
      .then(res => res.json())
      .then(data => {
        setUser(data);
        setName(data.name);
        setLoading(false);
      });
  }, [userId]);

  if (loading) return <div>Loading...</div>;

  return (
    <div className="card">
      {editing ? (
        <input value={name} onChange={e => setName(e.target.value)} />
      ) : (
        <h3>{user.name}</h3>
      )}
      <button onClick={() => setEditing(!editing)}>
        {editing ? 'Save' : 'Edit'}
      </button>
    </div>
  );
}
```

### Instructions for Refactoring
1. **Architecture & Decomposition**:
   - Extract stateful business logic into a custom hook or pure helper functions if appropriate.
   - Eliminate unnecessary re-renders, duplicate state derivations, and risky `useEffect` triggers.
2. **Accessibility & Semantics**:
   - Ensure semantic HTML, appropriate `aria-*` attributes, keyboard navigation (Enter, Space, Escape, Tab), and visible focus indicators.
3. **TypeScript Typing**:
   - Provide explicit interfaces for all props, event handlers, and data structures. Avoid implicit any.

### Instructions for Test Generation
1. Write a complete, copy-ready test file using **Vitest + React Testing Library**.
2. Cover:
   - Happy path rendering with default props.
   - User interactions (clicking, keyboard accessibility, typing).
   - Loading states, empty states, and error handling.
   - Asynchronous updates and cleanup.
3. Use accessible Testing Library query selectors (e.g., `getByRole`, `getByLabelText`) over test IDs or CSS classes.

How to Use This Prompt Effectively

  1. 1Paste your existing React component and choose your testing framework (Vitest or Jest).
  2. 2Select your primary priority (such as custom hook extraction, accessibility, or performance).
  3. 3Copy the output to get both the cleanly refactored component and the companion test file.

Representative AI Output

Sample output produced when using frontier AI models with the default parameters:

### Refactored Component
```tsx
import React, { useState } from 'react';
import { useUserProfile } from './useUserProfile';

export interface UserProfileCardProps {
  userId: string;
  onSave?: (newName: string) => Promise<void>;
}

export const UserProfileCard: React.FC<UserProfileCardProps> = ({ userId, onSave }) => {
  const { user, isLoading, error } = useUserProfile(userId);
  const [isEditing, setIsEditing] = useState(false);
  const [draftName, setDraftName] = useState('');

  // Accessible, clean rendering with loading & error boundaries...
};
```

### Vitest Unit Test File
```tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import { UserProfileCard } from './UserProfileCard';

describe('UserProfileCard', () => {
  it('renders loading state initially', () => {
    render(<UserProfileCard userId="123" />);
    expect(screen.getByRole('status')).toHaveTextContent(/loading/i);
  });
});
```

Pro Optimization & Edge-Case Tips

  • Prioritize `screen.getByRole` and `screen.getByLabelText` to simulate how real users and assistive technology interact with your UI.
  • Extract data fetching into custom hooks or TanStack Query queries so your UI components remain pure presentational views.
  • Use `userEvent.setup()` for realistic browser interaction simulations instead of legacy `fireEvent`.