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.
Customize & Generate Your Prompt
Adjust the variables below. Your customized prompt updates live in real-time ready to copy with zero setup.
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
- 1Paste your existing React component and choose your testing framework (Vitest or Jest).
- 2Select your primary priority (such as custom hook extraction, accessibility, or performance).
- 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`.
Related Tools on SPAUL Hub
More in Developers & Coding
View CategoryNext.js App Router Project Rules & AI Coding Agent Instructions
A comprehensive system prompt that transforms AI coding assistants (Claude 3.7, Cursor, ChatGPT, Gemini) into disciplined Next.js App Router architects. Prevents common hydration traps and enforce strict separation between Server and Client Components.
Supabase Edge Function Debugging & Security Review Prompt
Diagnose runtime errors, CORS header issues, environment variable leakage, and authentication token validation bugs in Supabase Deno Edge Functions.
AI Coding Agent Codebase Audit & Modernization Prompt
A structured audit prompt designed for AI coding agents to evaluate an unfamiliar codebase, identify security anti-patterns, spot performance bottlenecks, and generate prioritized action plans.