typescript-code-review
TypeScript and React code review guidelines (type safety, React patterns, performance). Auto-loads when reviewing TypeScript/React code.
What this skill does
# TypeScript/React Code Review Patterns
This skill provides TypeScript and React-specific code review guidelines. Use alongside `typescript-style` for comprehensive review.
## Critical Security Issues
### XSS Vulnerabilities
```typescript
// VULNERABLE - dangerouslySetInnerHTML without sanitization
<div dangerouslySetInnerHTML={{ __html: userInput }} />
// VULNERABLE - innerHTML assignment
element.innerHTML = userContent;
// SAFE - use DOMPurify
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />
// SAFER - avoid innerHTML entirely
<div>{userContent}</div> // React auto-escapes
```
### Insecure Data Exposure
```typescript
// VULNERABLE - logging sensitive data
console.log("User data:", user); // May include tokens, passwords
console.log("Request:", request.headers); // Auth headers
// VULNERABLE - exposing in error messages
throw new Error(`Auth failed for ${credentials}`);
// SAFE - sanitize before logging
console.log("User ID:", user.id); // Only necessary fields
```
### Unsafe eval/Function Constructor
```typescript
// VULNERABLE - code execution from strings
eval(userInput);
new Function(userInput)();
setTimeout(userInput, 1000); // String argument
// SAFE - avoid string evaluation
setTimeout(() => { processInput(userInput); }, 1000);
```
### Missing CSRF Protection
```typescript
// VULNERABLE - no CSRF token
fetch('/api/delete', { method: 'POST', body: data });
// SAFE - include CSRF token
fetch('/api/delete', {
method: 'POST',
headers: { 'X-CSRF-Token': csrfToken },
body: data,
});
```
## High Priority Type Safety Issues
### Unsafe Type Assertions
```typescript
// DANGEROUS - bypasses type checking
const user = data as User;
const items = response as any[];
// SAFER - use type guards
function isUser(data: unknown): data is User {
return typeof data === 'object' && data !== null && 'id' in data;
}
if (isUser(data)) {
// data is now typed as User
}
```
### Non-null Assertion Abuse
```typescript
// DANGEROUS - runtime error if null
const name = user!.profile!.name!;
// SAFE - explicit null handling
const name = user?.profile?.name ?? 'Unknown';
// Or with explicit checks
if (user?.profile?.name) {
const name = user.profile.name;
}
```
### Missing Error Handling in Async Code
```typescript
// BUG - unhandled promise rejection
async function fetchData() {
const response = await fetch(url);
return response.json(); // What if fetch fails?
}
// CORRECT - handle errors
async function fetchData() {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
} catch (error) {
console.error('Fetch failed:', error);
throw error; // Re-throw or return default
}
}
```
### Ignoring Promise Results
```typescript
// BUG - fire and forget
saveUser(userData); // No await, no error handling
// CORRECT
await saveUser(userData);
// or
saveUser(userData).catch(console.error);
```
## React Anti-Patterns
### Missing useEffect Dependencies
```typescript
// BUG - stale closure, missing dependency
useEffect(() => {
fetchUser(userId); // userId not in deps!
}, []); // Empty deps = runs once with initial userId
// CORRECT - include all dependencies
useEffect(() => {
fetchUser(userId);
}, [userId]);
```
### State Updates on Unmounted Components
```typescript
// BUG - memory leak, state update after unmount
useEffect(() => {
fetchData().then(setData);
}, []);
// CORRECT - cleanup with flag or AbortController
useEffect(() => {
let mounted = true;
fetchData().then((data) => {
if (mounted) setData(data);
});
return () => { mounted = false; };
}, []);
// BETTER - use AbortController
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(setData)
.catch(err => {
if (err.name !== 'AbortError') throw err;
});
return () => controller.abort();
}, [url]);
```
### Missing Key Prop in Lists
```typescript
// BUG - using index as key (causes issues on reorder)
items.map((item, index) => <Item key={index} data={item} />)
// CORRECT - use stable unique identifier
items.map((item) => <Item key={item.id} data={item} />)
```
### Inline Functions in JSX (Performance)
```typescript
// PERFORMANCE - new function on every render
<Button onClick={() => handleClick(id)} />
// BETTER - memoize if passed to memoized child
const handleButtonClick = useCallback(() => handleClick(id), [id]);
<MemoizedButton onClick={handleButtonClick} />
```
### Props Drilling Deep
```typescript
// CODE SMELL - passing props through many levels
<App user={user}>
<Layout user={user}>
<Sidebar user={user}>
<UserProfile user={user} />
// BETTER - use Context for cross-cutting concerns
const UserContext = createContext<User | null>(null);
<UserContext.Provider value={user}>
<App />
</UserContext.Provider>
```
## Performance Anti-Patterns
### Re-rendering Entire Lists
```typescript
// SLOW - all items re-render when one changes
function ItemList({ items }: { items: Item[] }) {
return items.map(item => <ItemRow item={item} />);
}
// FAST - memoize individual items
const MemoizedItemRow = memo(ItemRow);
function ItemList({ items }: { items: Item[] }) {
return items.map(item => <MemoizedItemRow key={item.id} item={item} />);
}
```
### Expensive Calculations Without Memoization
```typescript
// SLOW - recalculates on every render
function ExpensiveComponent({ data }: { data: number[] }) {
const sorted = [...data].sort((a, b) => a - b); // Every render!
const sum = data.reduce((a, b) => a + b, 0); // Every render!
return <div>{sorted.join(',')}: {sum}</div>;
}
// FAST - memoize expensive operations
function ExpensiveComponent({ data }: { data: number[] }) {
const sorted = useMemo(() => [...data].sort((a, b) => a - b), [data]);
const sum = useMemo(() => data.reduce((a, b) => a + b, 0), [data]);
return <div>{sorted.join(',')}: {sum}</div>;
}
```
### Unnecessary State
```typescript
// OVERHEAD - derived state should be computed
const [items, setItems] = useState<Item[]>([]);
const [itemCount, setItemCount] = useState(0); // Unnecessary!
// Update both when items change - easy to forget
setItems(newItems);
setItemCount(newItems.length); // Must keep in sync
// BETTER - derive from source of truth
const [items, setItems] = useState<Item[]>([]);
const itemCount = items.length; // Always in sync
```
### Large Bundle Imports
```typescript
// HEAVY - imports entire library
import _ from 'lodash';
import moment from 'moment'; // 300KB+
// LIGHT - import specific functions
import debounce from 'lodash/debounce';
import { format } from 'date-fns'; // Much smaller
```
## Accessibility Issues
### Missing ARIA Labels
```typescript
// INACCESSIBLE - icon-only button without label
<button onClick={onClose}>
<CloseIcon />
</button>
// ACCESSIBLE
<button onClick={onClose} aria-label="Close dialog">
<CloseIcon />
</button>
```
### Non-Interactive Elements with Handlers
```typescript
// INACCESSIBLE - div with click handler
<div onClick={handleClick}>Click me</div>
// ACCESSIBLE - use button or add role/keyboard
<button onClick={handleClick}>Click me</button>
// or
<div
role="button"
tabIndex={0}
onClick={handleClick}
onKeyDown={(e) => e.key === 'Enter' && handleClick()}
>
Click me
</div>
```
### Missing Form Labels
```typescript
// INACCESSIBLE - input without label
<input type="email" placeholder="Email" />
// ACCESSIBLE
<label>
Email
<input type="email" />
</label>
// or
<label htmlFor="email">Email</label>
<input id="email" type="email" />
```
### Color-Only Indicators
```typescript
// INACCESSIBLE - status only indicated by color
<span style={{ color: isError ? 'red' : 'green' }}>
{status}
</span>
// ACCESSIBLE - include text or icon
<span style={{ color: isError ? 'red' : 'green' }}>
{isError ? '❌ Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.