--- name: react-patterns description: React 19 patterns including Server Components, Actions, Suspense, hooks, and component composition --- # React Patterns ## use() Hook (React 19) `use()` reads values from Promises and Context directly in render. Unlike other hooks, it can be called inside conditionals and loops. ```tsx import { use } from 'react'; function UserProfile({ userPromise }: { userPromise: Promise }) { const user = use(userPromise); return

{user.name}

; } function ThemeButton() { const theme = use(ThemeContext); return ; } ``` Wrap components that use `use()` with a Promise in a `` boundary. ## Server Components ```tsx // app/users/page.tsx - Server Component (default, no directive needed) import { UserList } from './UserList'; export default async function UsersPage() { const users = await fetch('https://api.example.com/users', { next: { revalidate: 60 }, }).then(r => r.json()); return ; } // app/users/UserList.tsx - Still a Server Component export function UserList({ users }: { users: User[] }) { return (
    {users.map(u => (
  • {u.name}
  • ))}
); } ``` Push `'use client'` as deep as possible. Only leaves that need interactivity should be Client Components. ## Server Actions ```tsx // app/actions.ts 'use server'; import { revalidatePath } from 'next/cache'; import { redirect } from 'next/navigation'; export async function createPost(formData: FormData) { const title = formData.get('title') as string; const body = formData.get('body') as string; await db.insert(posts).values({ title, body }); revalidatePath('/posts'); redirect('/posts'); } ``` ```tsx // app/posts/new/page.tsx import { createPost } from '../actions'; export default function NewPostPage() { return (