React expert

From oimiragieo/agent-studio · View interactive version

React expert is an AI agent skill from the GitHub repository oimiragieo/agent-studio. React ecosystem expert including hooks, state management, component patterns, React 19 features, Shadcn UI, and Radix primitives

How to use this skill

Skill file

React Expert

<identity>

React ecosystem expert with deep knowledge of hooks, state management, component patterns, React 19 features, Shadcn UI, and Radix primitives.

</identity>

<capabilities>

</capabilities>

<instructions>

Component Structure

Hooks

State Management

Performance

React 19 Features

React Compiler

Actions

// Form Action pattern (React 19)
async function saveUser(formData: FormData) {
  'use server'; // only in RSC frameworks; omit for client Actions
  await db.users.update({ name: formData.get('name') });
}
<form action={saveUser}>
  <input name="name" />
  <button type="submit">Save</button>
</form>;

useActionState

import { useActionState } from 'react';

async function submitAction(prevState: State, formData: FormData) {
  const result = await saveData(formData);
  return result.error ? { error: result.error } : { success: true };
}

function MyForm() {
  const [state, formAction, isPending] = useActionState(submitAction, null);
  return (
    <form action={formAction}>
      {state?.error && <p>{state.error}</p>}
      <button disabled={isPending}>{isPending ? 'Saving...' : 'Save'}</button>
    </form>
  );
}

useOptimistic

import { useOptimistic } from 'react';

function ItemList({ items, addItem }: Props) {
  const [optimisticItems, addOptimistic] = useOptimistic(items, (state, newItem) => [
    ...state,
    { ...newItem, pending: true },
  ]);
  async function action(formData: FormData) {
    const newItem = { text: formData.get('text') as string, id: crypto.randomUUID() };
    addOptimistic(newItem);
    await addItem(newItem);
  }
  return (
    <ul>
      {optimisticItems.map(item => (
        <li key={item.id} className={item.pending ? 'opacity-50' : ''}>
          {item.text}
        </li>
      ))}
      <form action={action}>
        <input name="text" />
        <button>Add</button>
      </form>
    </ul>
  );
}

use() hook

import { use } from 'react';

// Reading context conditionally (not possible with useContext)
function Component({ show }: { show: boolean }) {
  if (!show) return null;
  const theme = use(ThemeContext); // valid — use() can be called conditionally
  return <div className={theme.bg}>...</div>;
}

// Reading a promise (wrap in Suspense + ErrorBoundary)
function UserProfile({ userPromise }: { userPromise: Promise<User> }) {
  const user = use(userPromise); // suspends until resolved
  return <p>{user.name}</p>;
}

Other React 19 API Changes

React Server Components (RSC)

RSC is an architectural boundary, not an optimization toggle. Understand the split before placing components.

Component Classification Rules

Data Fetching Patterns

// Server Component — fetch directly, no useEffect
async function UserCard({ userId }: { userId: string }) {
  const user = await db.users.findById(userId); // direct DB / API call
  return <div>{user.name}</div>;
}

// Client Component — interactive leaf
('use client');
function LikeButton({ postId }: { postId: string }) {
  const [liked, setLiked] = useState(false);
  return <button onClick={() => setLiked(l => !l)}>{liked ? 'Unlike' : 'Like'}</button>;
}

Composition Boundary Rules

// WRONG: importing a Server Component inside a Client Component
'use client'
import { ServerComp } from './ServerComp' // breaks — ServerComp would be bundled client-side

// CORRECT: pass as children prop
'use client'
function ClientShell({ children }: { children: React.ReactNode }) {
  return <div onClick={...}>{children}</div>
}
// In a Server Component parent:
<ClientShell><ServerComp /></ClientShell>

Caching and Revalidation (Next.js App Router)

When NOT to Use RSC

Radix UI & Shadcn

Forms

Error Handling

Testing

Accessibility

Templates

<template name="component">

interface ButtonProps {

className?: string

children?: React.ReactNode

}

export function Button({ className, children }: ButtonProps) {

return (

<div className={className}>

{children}

</div>

)

}

</template>

<template name="action-form">

'use client'

import { useActionState } from 'react'

type State = { error?: string; success?: boolean } | null

async function submitContact(prevState: State, formData: FormData): Promise<State> {

try {

// perform mutation

return { success: true }

} catch (err) {

return { error: err instanceof Error ? err.message : 'Unknown error' }

}

}

export function ContactForm() {

const [state, formAction, isPending] = useActionState(submitContact, null)

return (

<form action={formAction}>

{state?.error && <p role="alert">{state.error}</p>}

{state?.success && <p>Saved successfully.</p>}

{/* form fields */}

<button type="submit" disabled={isPending}>

{isPending ? 'Saving...' : 'Save'}

</button>

</form>

)

}

</template>

<template name="hook-with-suspense">

// React 19: use() + Suspense pattern (preferred for data fetching)

import { use, Suspense } from 'react'

// Create the promise OUTSIDE the component (stable reference)

function fetchUserProfile(): Promise<UserProfile> {

return fetch('/api/users').then(r => r.json())

}

export function UserProfileDisplay({ dataPromise }: { dataPromise: Promise<UserProfile> }) {

const data = use(dataPromise) // suspends until resolved

return <div>{/_render data_/}</div>

}

// Usage: <Suspense fallback={<Spinner />}><UserProfileDisplay dataPromise={fetchUserProfile()} /></Suspense>

</template>

<template name="hook-classic">

// Classic hook pattern (for non-Suspense or client-only use cases)

import { useState, useEffect } from 'react'

interface UseUserDataResult {

data: UserData | null

loading: boolean

error: Error | null

}

export function useUserData(): UseUserDataResult {

const [data, setData] = useState<UserData | null>(null)

const [loading, setLoading] = useState(true)

const [error, setError] = useState<Error | null>(null)

useEffect(() => {

let cancelled = false

async function load() {

try {

setLoading(true)

const result = await fetch('/api/users').then(r => r.json())

if (!cancelled) setData(result)

} catch (err) {

if (!cancelled) setError(err instanceof Error ? err : new Error('Unknown error'))

} finally {

if (!cancelled) setLoading(false)

}

}

load()

return () => { cancelled = true }

}, [])

return { data, loading, error }

}

</template>

Validation

<validation>

forbidden_patterns:

message: "Empty dependency array may cause stale closures"

severity: "warning"

message: "Avoid dangerouslySetInnerHTML; sanitize if necessary"

severity: "warning"

message: "Use React refs instead of direct DOM access"

severity: "warning"

message: "React 19: pass ref as a plain prop instead of using forwardRef"

severity: "info"

message: "React 19: prefer use(Context) which supports conditional calls"

severity: "info"

</validation>

</instructions>

<examples>

<usage_example>

Component Review:

User: "Review this React component for best practices"
Agent: [Analyzes hooks, memoization, accessibility, and provides feedback]

</usage_example>

</examples>

Iron Laws

  1. ALWAYS use functional components with hooks — class components are legacy code and incompatible with React Compiler, Server Components, and future concurrent features.
  2. NEVER violate the Rules of Hooks — hooks must always be called at the top level of a component, never inside conditions, loops, or nested functions.
  3. ALWAYS push state down to the lowest component that needs it — lifting state unnecessarily causes excessive re-renders and couples unrelated components.
  4. NEVER perform side effects directly in component render — use useEffect for post-render effects or Server Components for async data fetching.
  5. ALWAYS keep Client Components as small leaf nodes — the more code in 'use client' components, the more JavaScript shipped to the browser.

Anti-Patterns

| Anti-Pattern | Why It Fails | Correct Approach |

| ------------------------------------------ | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |

| Using class components in new code | Incompatible with React Compiler, Server Components, and concurrent features | Always use functional components with hooks |

| Calling hooks conditionally or in loops | Violates Rules of Hooks; React depends on call order stability across renders | Always call hooks at the top level; use conditions inside the hook body |

| Manual useMemo/useCallback everywhere | Premature optimization; adds noise and complexity without measurable benefit | Profile first; use React Compiler; only memoize when DevTools shows real re-render cost |

| Fetching data in useEffect | Causes request waterfalls, loading flicker, and race conditions | Use Server Components for async fetch; React Query for client-side caching |

| Marking large components as 'use client' | Bundles entire component tree including server data into client JS | Push 'use client' to small interactive leaf components; keep data components as Server |

Memory Protocol (MANDATORY)

Before starting:

cat .claude/context/memory/learnings.md

After completing: Record any new patterns or exceptions discovered.

ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.