SKILL.md
---
name: react-web
description: Modern React 19+ development with Server Components, Actions, hooks, TypeScript integration, and performance optimization. Use when building React web applications, implementing Server Components, using Actions for form handling, working with new hooks (use, useActionState, useOptimistic, useFormStatus), setting up React projects with Vite or Next.js, or optimizing React performance.
---
# React Web Development (React 19+)
Build modern, performant React applications using React 19+ features.
## Core Patterns
### Function Components with TypeScript
```tsx
interface ButtonProps {
variant?: 'primary' | 'secondary';
children: React.ReactNode;
onClick?: () => void;
}
export function Button({ variant = 'primary', children, onClick }: ButtonProps) {
return (
<button className={`btn btn-${variant}`} onClick={onClick}>
{children}
</button>
);
}
```
### Server Components (Default in React 19)
Server Components render on the server, reducing client JavaScript:
```tsx
// app/posts/page.tsx - Server Component (default)
async function PostList() {
const posts = await db.posts.findMany();
return (
<ul>
{posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
}
```
### Client Components
Mark interactive components with 'use client':
```tsx
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
```
## React 19 Features
### Actions & useActionState
Replace manual form handling with Actions:
```tsx
'use client';
import { useActionState } from 'react';
async function submitForm(prev: State, formData: FormData) {
'use server';
const name = formData.get('name');
await db.users.create({ name });
return { success: true };
}
function Form() {
const [state, action, pending] = useActionState(submitForm, { success: false });
return (
<form action={action}>
<input name="name" />
<button disabled={pending}>{pending ? 'Saving...' : 'Save'}</button>
</form>
);
}
```
### use() Hook for Promises & Context
```tsx
import { use } from 'react';
function UserProfile({ userPromise }) {
const user = use(userPromise); // Suspends until resolved
return <div>{user.name}</div>;
}
function ThemeButton() {
const theme = use(ThemeContext); // Read context conditionally
return <button style={{ color: theme.primary }}>Click</button>;
}
```
### useOptimistic for Instant UI Updates
```tsx
'use client';
import { useOptimistic } from 'react';
function TodoList({ todos, addTodo }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(state, newTodo) => [...state, { ...newTodo, pending: true }]
);
async function handleAdd(formData: FormData) {
const text = formData.get('text');
addOptimisticTodo({ text, id: Date.now() });
await addTodo(text);
}
return (
<form action={handleAdd}>
<input name="text" />
<ul>
{optimisticTodos.map(todo => (
<li key={todo.id} style={{ opacity: todo.pending ? 0.5 : 1 }}>
{todo.text}
</li>
))}
</ul>
</form>
);
}
```
### useFormStatus for Form State
```tsx
'use client';
import { useFormStatus } from 'react-dom';
function SubmitButton() {
const { pending } = useFormStatus();
return <button disabled={pending}>{pending ? 'Submitting...' : 'Submit'}</button>;
}
```
## Project Structure
```
src/
├── app/ # App Router (Next.js) or routes
├── components/
│ ├── ui/ # Reusable UI primitives
│ ├── features/ # Feature-specific components
│ └── layouts/ # Layout components
├── hooks/ # Custom hooks
├── lib/ # Utilities, API clients
├── types/ # TypeScript types
└── styles/ # Global styles, tokens
```
## Custom Hooks Pattern
```tsx
function useAsync<T>(asyncFn: () => Promise<T>, deps: unknown[]) {
const [state, setState] = useState<{
data: T | null;
loading: boolean;
error: Error | null;
}>({ data: null, loading: true, error: null });
useEffect(() => {
setState(s => ({ ...s, loading: true }));
asyncFn()
.then(data => setState({ data, loading: false, error: null }))
.catch(error => setState({ data: null, loading: false, error }));
}, deps);
return state;
}
```
## Performance Guidelines
1. **Let React Compiler optimize** - React 19's compiler auto-memoizes; avoid manual useMemo/useCallback unless profiling shows need
2. **Use Server Components** - Default to server rendering, add 'use client' only for interactivity
3. **Lazy load routes** - Use `React.lazy()` and Suspense for code splitting
4. **Avoid prop drilling** - Use Context or composition patterns
## Related Skills
- **Atomic Design**: Component hierarchy patterns → See `references/atomic-integration.md`
- **CSS Tokens**: Styling with design tokens → See `references/styling-patterns.md`
- **Storybook**: Component documentation → See `references/storybook-setup.md`
references/hooks-reference.md
# React 19 Hooks Reference
## Core Hooks
### useState
Manage local component state.
```tsx
const [value, setValue] = useState<T>(initialValue);
```
### useEffect
Side effects, subscriptions, DOM mutations.
```tsx
useEffect(() => {
// effect
return () => { /* cleanup */ };
}, [dependencies]);
```
### useContext
Access context value.
```tsx
const value = useContext(MyContext);
```
### useRef
Mutable ref that persists across renders.
```tsx
const ref = useRef<HTMLInputElement>(null);
```
### useMemo
Memoize expensive computations.
```tsx
const memoized = useMemo(() => expensiveCalc(a, b), [a, b]);
```
### useCallback
Memoize callback functions.
```tsx
const callback = useCallback(() => doSomething(a), [a]);
```
## React 19 New Hooks
### use
Read promises and context in render (can be conditional).
```tsx
const data = use(promise);
const theme = use(ThemeContext);
```
### useActionState
Handle form actions with state.
```tsx
const [state, formAction, isPending] = useActionState(
async (prevState, formData) => { /* action */ },
initialState
);
```
### useFormStatus
Access parent form's submission state.
```tsx
const { pending, data, method, action } = useFormStatus();
```
### useOptimistic
Optimistic UI updates during async operations.
```tsx
const [optimisticState, addOptimistic] = useOptimistic(
state,
(currentState, optimisticValue) => newState
);
```
### useTransition
Mark updates as non-blocking transitions.
```tsx
const [isPending, startTransition] = useTransition();
startTransition(() => setSlowState(newValue));
```
### useDeferredValue
Defer re-rendering of non-urgent updates.
```tsx
const deferredValue = useDeferredValue(value);
```
### useId
Generate unique IDs for accessibility.
```tsx
const id = useId(); // e.g., ":r1:"
```
## Custom Hook Patterns
### useLocalStorage
```tsx
function useLocalStorage<T>(key: string, initialValue: T) {
const [stored, setStored] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
const setValue = (value: T | ((val: T) => T)) => {
const valueToStore = value instanceof Function ? value(stored) : value;
setStored(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
};
return [stored, setValue] as const;
}
```
### useDebounce
```tsx
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
```
### useMediaQuery
```tsx
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(
() => window.matchMedia(query).matches
);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
mediaQuery.addEventListener('change', handler);
return () => mediaQuery.removeEventListener('change', handler);
}, [query]);
return matches;
}
```
references/styling-patterns.md
# React Styling Patterns
## CSS Modules
Scoped CSS with automatic class name generation.
```tsx
// Button.module.css
.button { padding: 8px 16px; }
.primary { background: var(--color-primary); }
// Button.tsx
import styles from './Button.module.css';
export function Button({ variant = 'primary', children }) {
return (
<button className={`${styles.button} ${styles[variant]}`}>
{children}
</button>
);
}
```
## Tailwind CSS
Utility-first CSS with React.
```tsx
export function Card({ children }) {
return (
<div className="rounded-lg shadow-md p-4 bg-white dark:bg-gray-800">
{children}
</div>
);
}
```
### With clsx for conditional classes:
```tsx
import clsx from 'clsx';
function Button({ variant, disabled, children }) {
return (
<button
className={clsx(
'px-4 py-2 rounded font-medium',
variant === 'primary' && 'bg-blue-500 text-white',
variant === 'secondary' && 'bg-gray-200 text-gray-800',
disabled && 'opacity-50 cursor-not-allowed'
)}
>
{children}
</button>
);
}
```
## CSS-in-JS with styled-components
```tsx
import styled from 'styled-components';
const Button = styled.button<{ $primary?: boolean }>`
padding: 8px 16px;
border-radius: 4px;
background: ${props => props.$primary ? 'var(--color-primary)' : 'transparent'};
color: ${props => props.$primary ? 'white' : 'var(--color-text)'};
`;
```
## Design Tokens Integration
Use CSS custom properties for theming:
```css
/* tokens.css */
:root {
--color-primary: #2563eb;
--color-secondary: #64748b;
--spacing-sm: 8px;
--spacing-md: 16px;
--radius-md: 8px;
}
[data-theme="dark"] {
--color-primary: #3b82f6;
--color-background: #1e293b;
}
```
```tsx
// Access in React
function ThemedButton() {
return (
<button style={{
background: 'var(--color-primary)',
padding: 'var(--spacing-md)',
borderRadius: 'var(--radius-md)'
}}>
Themed Button
</button>
);
}
```
## CSS Container Queries
Component-responsive styling:
```css
.card-container {
container-type: inline-size;
}
@container (min-width: 400px) {
.card { display: flex; }
}
```