AgentSkillsCN

react-web-development

使用 TypeScript、Zustand、React Query/Axios 以及 React Router,打造现代化的 React 应用程序。无论是(1)以 TypeScript 创建全新 React 应用,(2)借助 Zustand 或 React Query 实现状态管理,(3)通过 Axios 实现 API 集成,(4)配置受保护路由的路由策略,还是(5)构建身份认证流程,此技能都能助您游刃有余。

SKILL.md
--- frontmatter
name: react-web-development
description: Build modern React applications with TypeScript, Zustand, React Query/Axios, and React Router. Use when (1) creating a new React app with TypeScript, (2) setting up state management with Zustand or React Query, (3) implementing API integration with Axios, (4) configuring routing with protected routes, or (5) building authentication flows

React Web Development

Build production-ready React applications with modern tooling and best practices.

Tech Stack

  • React 18+ with TypeScript
  • Vite for fast development
  • React Compiler (experimental) for auto-optimization
  • Zustand for client state
  • React Query + Axios for server state
  • React Router v6+ for navigation
  • ErrorBoundary + Suspense for error and loading states
  • CSS Variables for theming

Quick Start

1. Create Project

bash
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install zustand @tanstack/react-query axios react-router-dom
npm install -D babel-plugin-react-compiler
npm run dev

For detailed setup including React Compiler configuration, see setup-guide.md.

2. Configure TypeScript

Enable strict mode in tsconfig.json. See typescript-patterns.md for complete configuration.

3. Setup State Management

Client state (Zustand): UI state, auth, preferences
Server state (React Query): API data, caching

typescript
// Example: Auth Store with Zustand
import { create } from "zustand";
import { persist } from "zustand/middleware";

export const useAuthStore = create()(
  persist(
    (set) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      login: (user, token) => set({ user, token, isAuthenticated: true }),
      logout: () => set({ user: null, token: null, isAuthenticated: false }),
    }),
    { name: "auth-storage" }
  )
);

For complete patterns, see state-management.md.

4. Setup React Query + Axios

typescript
// src/main.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000,
      retry: 1,
    },
  },
});

ReactDOM.createRoot(document.getElementById("root")!).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

For Axios setup and API patterns, see state-management.md.

5. Configure Routing

typescript
// src/router/index.tsx
import { createBrowserRouter } from "react-router-dom";

export const router = createBrowserRouter([
  {
    path: "/",
    element: <RootLayout />,
    children: [
      { index: true, element: <HomePage /> },
      { path: "login", element: <LoginPage /> },
      {
        path: "users",
        element: (
          <ProtectedRoute>
            <UsersPage />
          </ProtectedRoute>
        ),
      },
    ],
  },
]);

For protected routes and advanced patterns, see routing.md.

Workflows

Creating a New Feature

  1. Define types - Create interfaces in src/types/
  2. Setup API - Create endpoint functions in src/api/endpoints/
  3. Create hooks - React Query hooks in src/hooks/
  4. Build UI - Components with TypeScript props
  5. Add routing - Configure routes in src/router/

Implementing Authentication

  1. Create auth store (Zustand) - Store access token in memory only
  2. Setup Axios interceptors - Auto-refresh on 401
  3. Create login/logout flows - See authentication.md
  4. Add protected routes - See routing.md

Key principle: Access token in memory, refresh token in httpOnly cookie.

Example:

typescript
import { useMutation } from "@tanstack/react-query";
import { useAuthStore } from "../store/useAuthStore";
import { useNavigate } from "react-router-dom";
import apiClient from "../api/client";

export default function LoginPage() {
  const navigate = useNavigate();
  const login = useAuthStore((state) => state.login);

  const loginMutation = useMutation({
    mutationFn: (credentials: { email: string; password: string }) =>
      apiClient.post("/auth/login", credentials),
    onSuccess: (response) => {
      login(response.data.user, response.data.token);
      navigate("/dashboard");
    },
  });

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        loginMutation.mutate({ email, password });
      }}
    >
      ...
    </form>
  );
}

API Integration Pattern

  1. Define types - Request/response interfaces
  2. Create API functions - In src/api/endpoints/
  3. Create React Query hooks - Queries and mutations
  4. Use in components - Handle loading, error, success states

Example:

typescript
// 1. Types
export interface User {
  id: number;
  name: string;
  email: string;
}

// 2. API functions
export const usersApi = {
  getAll: () => apiClient.get<User[]>('/users'),
  create: (data: Omit<User, 'id'>) => apiClient.post<User>('/users', data),
};

// 3. React Query hooks
export const useUsers = () =>
  useQuery({
    queryKey: ['users'],
    queryFn: async () => (await usersApi.getAll()).data,
  });

// 4. Use in component
function UsersPage() {
  const { data: users, isLoading } = useUsers();

  if (isLoading) return <div>Loading...</div>;
  return <div>{users?.map(user => ...)}</div>;
}

For complete patterns, see state-management.md.

6. Setup Error Handling

Wrap app with ErrorBoundary and Suspense:

typescript
import { ErrorBoundary } from "./components/ErrorBoundary";
import { Suspense } from "react";

function App() {
  return (
    <ErrorBoundary fallback={<ErrorScreen />}>
      <Suspense fallback={<LoadingScreen />}>
        <Router />
      </Suspense>
    </ErrorBoundary>
  );
}

For ErrorBoundary implementation and Suspense patterns, see error-handling.md.

Design System

Use CSS variables for consistent theming:

css
:root {
  --primary: hsl(220, 80%, 50%);
  --spacing-md: 1rem;
  --radius-md: 8px;
  --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.15);
  --transition-normal: 250ms ease-in-out;
}

.button {
  padding: var(--spacing-md);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-md);
  transition: all var(--transition-normal);
}

For complete design system, see design-system.md.

Verification Checklist

Before deployment:

  • TypeScript strict mode enabled, no errors
  • Zustand setup for client state
  • React Query setup for all API calls
  • Axios interceptors configured (auth, errors)
  • React Router with protected routes
  • Responsive design tested
  • Loading and error states handled
  • No console errors or warnings

For detailed verification, see setup-guide.md.

Reference Files

  • setup-guide.md - Project initialization, React Compiler setup, folder structure, environment setup
  • typescript-patterns.md - TypeScript configuration, type definitions, component props
  • state-management.md - Zustand stores, React Query hooks, Axios setup
  • routing.md - React Router setup, protected routes, navigation patterns
  • authentication.md - Token management, login/logout, refresh patterns, security best practices
  • error-handling.md - ErrorBoundary, Suspense, loading skeletons, error patterns
  • design-system.md - CSS variables, component styles, animations, theming

Best Practices

State Management

  • Zustand for client state (UI, auth, preferences)
  • React Query for server state (API data, caching)
  • Never mix - keep responsibilities separate

TypeScript

  • Enable strict mode
  • Define interfaces for all data
  • Type all component props
  • Avoid any - use unknown if needed

API Layer

  • Use Axios interceptors for auth
  • Handle errors globally
  • Invalidate queries after mutations
  • Implement loading and error states

Routing

  • Use nested routes for layouts
  • Implement protected routes
  • Save location state for redirects
  • Lazy load large pages

Styling

  • Use CSS variables for theming
  • Mobile-first responsive design
  • Add smooth transitions
  • Implement dark mode support