React Prompt Templates
Cập nhật: 03/2026
Essential Aspects & Prompt Templates
1. Components
Template 1.1: Tạo Functional Component
<role>Senior React developer chuyên component architecture</role>
<action>
Tạo functional component [TÊN_COMPONENT] với props [DANH_SÁCH_PROPS]
</action>
<context>
- Dự án: React [VERSION] + TypeScript
- Styling: [TAILWIND_CSS/CSS_MODULES/STYLED_COMPONENTS]
- Component type: [PRESENTATIONAL/CONTAINER]
- Cần đọc existing components để học patterns, conventions và tái sử dụng components có sẵn
</context>
<expectation>
- TypeScript với proper interface cho props
- Export default component
- JSX semantic và accessible (article, section, header tags)
- Props destructuring trong function parameters
- PropTypes hoặc TypeScript interface
- File output: src/components/[tên-component].tsx
- Naming convention: PascalCase cho component, kebab-case cho file
</expectation>
Template 1.2: Refactor Class Component sang Functional
<role>Senior React developer chuyên modernization và refactoring</role>
<action>
Refactor class component [TÊN_COMPONENT] sang functional component với hooks
</action>
<context>
- Component hiện tại: [ĐƯỜng_DẪN_FILE]
- State management: [ZUSTAND/REDUX/CONTEXT_API]
- Lifecycle methods đang dùng: [componentDidMount, componentDidUpdate, componentWillUnmount, etc.]
- Dependencies: [LIỆT_KÊ_DEPENDENCIES]
- Cần đọc existing functional components để học hook patterns
</context>
<expectation>
- Convert this.state → useState hooks
- Convert lifecycle methods → useEffect hooks
- Convert instance methods → regular functions hoặc useCallback
- Convert this.props → destructured props
- Giữ nguyên 100% functionality
- All existing tests phải pass without modification
- Performance không giảm (use React.memo nếu cần)
- Type safety với TypeScript maintained
</expectation>
2. React Hooks
Template 2.1: useState Hook Implementation
<role>Senior React developer chuyên hooks patterns</role>
<action>
Implement state management cho [FEATURE] sử dụng useState hook
</action>
<context>
- Feature: [MÔ_TẢ_FEATURE]
- State cần quản lý: [LIỆT_KÊ_STATE_PROPERTIES]
- State updates: [SYNCHRONOUS/ASYNCHRONOUS]
- Related components: [LIỆT_KÊ_COMPONENTS]
- Cần đọc existing hooks usage để học patterns
</context>
<expectation>
- useState với proper TypeScript types
- State initialization với appropriate default values
- State update functions: setter functions với descriptive names
- Handle complex state: objects/arrays với immutable updates
- Edge cases handling: undefined, null, empty states
- State updates với functional form khi depend on previous state
- No unnecessary re-renders (check with React DevTools)
</expectation>
Template 2.2: useEffect Hook - Side Effects
<role>Senior React developer chuyên side effects và lifecycle</role>
<action>
Implement useEffect hook cho [SIDE_EFFECT] trong component [TÊN_COMPONENT]
</action>
<context>
- Side effect type: [DATA_FETCHING/SUBSCRIPTION/DOM_MANIPULATION/ANALYTICS]
- Timing: [ON_MOUNT/ON_UPDATE/ON_UNMOUNT]
- Dependencies: [LIỆT_KÊ_DEPENDENCIES]
- Cleanup needed: [YES/NO]
- Alternative approaches available: [SERVER_COMPONENTS/TANSTACK_QUERY/SWR]
- Cần review: https://react.dev/learn/you-might-not-need-an-effect
</context>
<expectation>
- useEffect với correct dependency array
- Cleanup function return nếu có subscriptions/timers
- AbortController cho fetch requests để cancel on unmount
- ESLint exhaustive-deps warnings resolved
- Handle race conditions nếu có multiple async operations
- Loading, error, success states properly managed
- KHÔNG dùng useEffect nếu có better alternatives (Server Components, TanStack Query)
- TypeScript types cho fetched data
</expectation>
Template 2.3: Custom Hook Development
<role>Senior React engineer chuyên reusable hooks architecture</role>
<action>
Tạo custom hook [TÊN_HOOK] để encapsulate logic [MÔ_TẢ_LOGIC]
</action>
<context>
- Logic cần extract: [MÔ_TẢ_LOGIC_CHI_TIẾT]
- Components sẽ sử dụng: [LIỆT_KÊ_COMPONENTS] (tối thiểu 2 components)
- Built-in hooks sử dụng: [useState, useEffect, useCallback, useMemo, etc.]
- External dependencies: [LIBRARIES_NẾU_CÓ]
- Cần đọc existing custom hooks trong src/hooks/ để học patterns
</context>
<expectation>
- Hook name bắt đầu với "use" prefix (useLocalStorage, useDebounce, etc.)
- TypeScript generics cho type safety: function useHook<T>
- Clear API design: parameters và return value intuitive
- JSDoc comments giải thích usage và examples
- Follow Rules of Hooks: chỉ call ở top level
- Handle cleanup properly trong useEffect
- Unit tests với @testing-library/react-hooks
- Error handling graceful
- File output: src/hooks/[use-hook-name].ts
</expectation>
3. State Management
Template 3.1: Context API Implementation
<role>Senior React developer chuyên state architecture</role>
<action>
Tạo Context provider cho [FEATURE] để share state across components
</action>
<context>
- Feature: [TÊN_FEATURE]
- State cần share: [LIỆT_KÊ_STATE]
- Components cần access: [LIỆT_KÊ_COMPONENTS]
- State complexity: [SIMPLE/COMPLEX]
- Update frequency: [LOW/MEDIUM/HIGH]
- Cần đọc existing contexts trong src/contexts/ để học patterns
</context>
<expectation>
- Create Context với TypeScript types
- Provider component với useState hoặc useReducer
- Custom hook để consume context: use[Feature]Context
- Throw error nếu hook used outside Provider
- Prevent unnecessary re-renders: useMemo cho context value
- useCallback cho action functions
- Separate Provider và Consumer logic
- Export Provider và custom hook only (not raw Context)
- File output: src/contexts/[feature-context].tsx
</expectation>
Template 3.2: Zustand Store Setup
<role>React developer chuyên state management với Zustand</role>
<action>
Thiết kế và implement Zustand store cho [FEATURE]
</action>
<context>
- Feature: [TÊN_FEATURE]
- State shape: [LIỆT_KÊ_STATE_PROPERTIES]
- Actions: [LIỆT_KÊ_ACTIONS]
- Computed values: [DERIVED_STATE_NẾU_CÓ]
- Persistence: [YES/NO] - localStorage/sessionStorage
- Cần đọc existing stores trong src/stores/ để học patterns
</context>
<expectation>
- TypeScript interface cho state shape
- create() từ zustand với typed state
- State actions với immer middleware nếu có nested updates
- Selectors để optimize re-renders
- Middleware: persist (nếu cần), devtools (development)
- KHÔNG store derived state (use selectors instead)
- Naming convention: [feature]Store (cartStore, authStore)
- File output: src/stores/[feature]-store.ts
- Components subscribe chỉ data cần thiết
</expectation>
4. Performance Optimization
Template 4.1: React.memo & Memoization
<role>Performance optimization specialist chuyên React rendering</role>
<action>
Optimize component [TÊN_COMPONENT] để giảm unnecessary re-renders
</action>
<context>
- Component: [ĐƯỜng_DẪN]
- Performance issue: [MÔ_TẢ_VẤN_ĐỀ]
- React DevTools Profiler data: [SỐ_LIỆU_RENDER_COUNT]
- Parent components: [LIỆT_KÊ_PARENTS]
- Props stability: [STABLE/UNSTABLE]
- Cần measure với React DevTools Profiler trước khi optimize
</context>
<expectation>
- KHÔNG premature optimization (measure first)
- React.memo wrapper nếu props ít thay đổi
- Custom comparison function nếu cần: React.memo(Component, arePropsEqual)
- useMemo cho expensive calculations
- useCallback cho callback props passed to memoized children
- Profiler measurements: before vs after optimization
- Document WHY memoization needed (comment in code)
- Trade-offs explained: memory vs CPU
</expectation>
Template 4.2: Code Splitting & Lazy Loading
<role>Performance engineer chuyên bundle optimization</role>
<action>
Implement code splitting cho [ROUTES/COMPONENTS] để reduce initial bundle size
</action>
<context>
- Current bundle size: [SIZE_MB]
- Performance metrics: FCP [MS], LCP [MS], TTI [MS]
- Target improvement: [PERCENTAGE]% reduction
- Routes/components to split: [LIỆT_KÊ_ROUTES_COMPONENTS]
- Bundler: [VITE/WEBPACK/ROLLUP]
- Cần analyze bundle với [webpack-bundle-analyzer/vite-plugin-visualizer]
</context>
<expectation>
- React.lazy() cho dynamic imports
- Suspense boundaries với loading fallback UI
- Error boundaries để handle chunk load failures
- Route-based splitting: lazy load page components
- Component-based splitting cho heavy components
- Preload critical routes: <link rel="prefetch">
- Custom chunk names trong dynamic imports: /* webpackChunkName: "name" */
- Measure improvement: Lighthouse score before/after
- File size report: analyze bundle composition
</expectation>
5. Forms & Validation
Template 5.1: React Hook Form + Zod
<role>Senior React developer chuyên forms và validation</role>
<action>
Xây dựng form [TÊN_FORM] với validation sử dụng React Hook Form + Zod
</action>
<context>
- Form type: [LOGIN/REGISTRATION/CHECKOUT/CONTACT/etc.]
- Fields: [LIỆT_KÊ_FIELDS_VÀ_TYPES]
- Validation rules: [LIỆT_KÊ_RULES_CHI_TIẾT]
- Submit action: [API_ENDPOINT] hoặc [LOCAL_ACTION]
- Error handling: [INLINE/TOAST/MODAL]
- Cần đọc existing forms để học validation patterns
</context>
<expectation>
- Zod schema definition với proper types
- useForm hook với zodResolver
- register() cho input fields
- handleSubmit() cho form submission
- Validation errors display dưới mỗi field
- FormState: isSubmitting, isValid, errors
- Disable submit button khi isSubmitting hoặc !isValid
- Reset form after successful submission
- TypeScript type inference từ Zod schema
- Accessible form: labels, aria-describedby cho errors
- File output: src/components/forms/[form-name].tsx
</expectation>
6. API Integration
Template 6.1: Data Fetching với TanStack Query
<role>Senior React developer chuyên server state management</role>
<action>
Implement data fetching cho [FEATURE] sử dụng TanStack Query (React Query)
</action>
<context>
- API endpoints: [METHOD] [URL]
- Request payload: [STRUCTURE]
- Response format: [STRUCTURE]
- Authentication: [BEARER_TOKEN/API_KEY/NONE]
- Caching strategy: [STALE_TIME/CACHE_TIME]
- Refetch triggers: [ON_WINDOW_FOCUS/ON_RECONNECT/INTERVAL]
- Cần đọc existing query hooks trong src/hooks/api/ để học patterns
- Cần setup QueryClientProvider nếu chưa có
</context>
<expectation>
- QueryClientProvider trong App.tsx với queryClient config
- useQuery cho GET requests: useQuery({ queryKey, queryFn })
- useMutation cho POST/PUT/DELETE: useMutation({ mutationFn })
- Query keys consistent: ['resource', resourceId] format
- Query functions type-safe với TypeScript
- Error handling: useQuery error state hoặc Error Boundary
- Loading states: isLoading, isFetching, isError from useQuery
- Optimistic updates với onMutate callback (nếu cần)
- Cache invalidation: queryClient.invalidateQueries()
- Refetch policies: staleTime, gcTime configured
- Custom query hooks: wrap useQuery trong custom hook cho reusability
- File output: src/hooks/api/[use-hook-name].ts
</expectation>
7. Routing
Template 7.1: React Router v6 Setup
<role>Frontend developer chuyên routing architecture</role>
<action>
Setup React Router v6 cho application với [SỐ_ROUTES] routes
</action>
<context>
- Routes: [LIỆT_KÊ_ROUTES_VÀ_PATHS]
- Protected routes: [ROUTES_CẦN_AUTH]
- Layout components: [LAYOUTS]
- Nested routes: [YES/NO]
- 404 handling: [STRATEGY]
- Cần design route structure trước khi implement
</context>
<expectation>
- BrowserRouter wrapper trong main.tsx
- Routes definition với createBrowserRouter (data router API)
- Route objects: path, element, loader, errorElement
- Protected routes: wrapper component check authentication
- Lazy loading cho route components: lazy(() => import())
- Suspense boundaries cho lazy routes
- 404 route với wildcard path: "*"
- Nested routes với Outlet component
- Type-safe navigation: useNavigate() với TypeScript
- File structure: src/routes/ hoặc src/pages/
</expectation>
8. Testing
Template 8.1: Component Testing với React Testing Library
<role>QA Engineer chuyên React Testing Library</role>
<action>
Viết comprehensive tests cho component [TÊN_COMPONENT]
</action>
<context>
- Component: [ĐƯỜng_DẪN]
- Component type: [PRESENTATIONAL/CONTAINER/FORM]
- Props: [LIỆT_KÊ_PROPS]
- User interactions: [CLICKS/TYPING/SUBMISSIONS]
- External dependencies: [API_CALLS/CONTEXT/ROUTER]
- Cần đọc existing tests để học testing patterns
</context>
<expectation>
- Test file: [component-name].test.tsx
- Testing Library queries: getByRole, getByLabelText (accessible queries)
- KHÔNG test implementation details (internal state, private methods)
- Test user-visible behavior only
- Render component: render(<Component />)
- User interactions: userEvent.click(), userEvent.type()
- Assertions: screen.getByText(), expect().toBeInTheDocument()
- Mock external dependencies: API calls với MSW, context với wrapper
- Async testing: await waitFor(), await screen.findBy...()
- Coverage target: >= 80% cho critical components
- File: src/components/__tests__/[component-name].test.tsx
</expectation>
Best Practices Checklist
Khi viết prompt cho React, đảm bảo:
- ✅ Chỉ định React version (18.x, 19.x)
- ✅ TypeScript với strict mode
- ✅ Styling solution rõ ràng (Tailwind, CSS Modules, styled-components)
- ✅ Đọc existing code để học patterns
- ✅ Accessibility (semantic HTML, ARIA labels, keyboard navigation)
- ✅ Error handling comprehensive
- ✅ TypeScript types/interfaces đầy đủ
- ✅ File paths và naming conventions
- ✅ Performance considerations (React.memo, code splitting)
- ✅ Testing strategy (unit + integration)