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 & Customize This Prompt
Fill in your target framework, environment rules, or source metrics in the interactive builder above. The assembled template updates instantly.
Click "Copy Prompt to Clipboard". You can copy the full assembled text or copy system instructions separately.
Refer to the Model Guidance below to choose the highest-performing frontier model or local runtime for this specific task.
Paste into your AI coding tool, chat interface, or local Ollama runtime. Verify syntax, types, and schema compliance against expected output.
Workflow Guidance
- Paste your existing React component and choose your testing framework (Vitest or Jest).
- Select your primary priority (such as custom hook extraction, accessibility, or performance).
- Copy 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`.
Recommended AI Models for Coding & Full-Stack Engineering
Frontier models tested against Next.js 15, TypeScript 5.6, Supabase, and automated unit test generation.
Claude 3.5 Sonnet
Deep codebase reasoning, complex Next.js App Router rules, and full test suites without omissions.
- Unrivaled understanding of modern React 19 / Next.js Server Components
- Strict compliance with system instructions without skipping edge-case checks
- Generates syntactically complete Vitest and RTL mocks
OpenAI GPT-4o
Rapid iterative debugging, Supabase function logging, and strict JSON output schemas.
- Sub-second first-token latency for fast dev loops
- Excellent function-calling and schema validation reliability
- Accurate regex generation and API endpoint routing
DeepSeek-Coder V2
Local inference and budget-friendly batch refactoring across large file trees.
- 236B MoE architecture competitive with proprietary frontier models
- Strong 128K context window for multi-file dependency trees
- Available via Ollama and vLLM for self-hosted private workflows
Copy your assembled prompt and test immediately with approved frontier models or your own API key.
Also Checkout
Verify AI-generated media, inspect deep image/video provenance, check C2PA cryptographic manifests, and strip sensitive EXIF tags with our 100% private, client-side tools.
AI Media Detector
Verify whether an image or video is AI-generated, check C2PA cryptographic manifests, and detect synthetic provenance markers.
Photo Metadata Viewer
Inspect deep EXIF, IPTC, and XMP metadata, view camera optics and GPS coordinates, and strip metadata to protect your privacy.
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.