Act as a Senior React Developer. Write a responsive Navigation Bar component using React 18, TypeScript, and Tailwind CSS.
Requirements:
- Include desktop navigation links and a mobile hamburger menu.
- Use React `useState` to control mobile drawer visibility.
- Close the drawer on ESC key press and when clicking outside.
- Ensure proper ARIA attributes (`aria-expanded`, `aria-label`).
- Export explicit TypeScript interface for navigation items (`{ label: string; href: string; icon?: React.ReactNode }`).
- Provide pure, runnable code with no inline styles.
Write a Next.js `middleware.ts` file that executes on the Edge Runtime.
Requirements:
1. Protect `/dashboard/*` and `/admin/*` routes, redirecting unauthenticated users to `/login?callbackUrl=...`.
2. Allow public access to `/`, `/login`, `/register`, and `/api/webhooks/*`.
3. Add custom HTTP security headers (CSP, X-Frame-Options, Referrer-Policy) to all outgoing responses.
4. Export an optimized `config` matcher object to prevent middleware from executing on static assets or image requests.
Create a reusable Modal Dialog component in React using TypeScript and Tailwind CSS.
Requirements:
- Props: `isOpen` (boolean), `onClose` () => void, `title` (string), `children` (React.ReactNode).
- Trap focus within the modal when open using pure React refs (or focus-trap pattern).
- Prevent background page scrolling when modal is open.
- Handle Keyboard events: 'Escape' key must trigger `onClose`.
- Include smooth transition backdrop animations.
Write a functional React component in TypeScript that implements an infinite scroll list using the Intersection Observer API.
Requirements:
- Do not use external libraries for scrolling.
- Fetch paginated mock data asynchronously when the sentinel element enters the viewport.
- Include explicit visual loading indicators, end-of-list indicator, and error recovery buttons.
- Handle cleanup for the Intersection Observer properly inside `useEffect`.
Act as a React Lead. Build a 3-step User Onboarding Form component using React 18, TypeScript, and React Hook Form with Zod validation schema.
Requirements:
- Step 1: Account Info (Email, Password).
- Step 2: Profile Details (Full Name, Avatar URL).
- Step 3: Confirmation and Summary.
- Allow users to move back and forth without losing step data.
- Validate inputs per step before allowing navigation to the next step.
Write a generic Data Table component in React with TypeScript (`TableProps<T>`).
Requirements:
- Accept `data: T[]` and dynamic `columns` config array containing `header`, `accessorKey`, and optional `sortable` flag.
- Provide client-side column sorting (ascending/descending toggle).
- Include a global text search input that filters rows across all visible text fields.
- Style cleanly using Tailwind CSS with alternating row colors.
Write a custom React hook named `useLocalStorage<T>` in TypeScript.
Requirements:
- Sync state value with `window.localStorage`.
- Handle JSON serialization and deserialization safely with try/catch blocks.
- Listen to window 'storage' events so changes in one browser tab update the hook state in other open tabs.
- Provide initial value fallback support.
Create a global e-commerce shopping cart store using Zustand and TypeScript.
Requirements:
- Cart Item state: `id`, `title`, `price`, `quantity`, `image`.
- Actions: `addItem`, `removeItem`, `updateQuantity`, `clearCart`.
- Derived selectors: `totalItemsCount` and `totalCartPrice`.
- Persist cart state to localStorage automatically using Zustand middleware.
Generate a Redux Toolkit slice (`authSlice.ts`) for managing user authentication state using TypeScript.
Requirements:
- Initial state: `user`, `token`, `isAuthenticated`, `isLoading`, `error`.
- Include extraReducers for async thunks: `loginUser`, `logoutUser`, and `fetchCurrentUser`.
- Export strongly typed selectors and actions.
Write a lightweight, typed `useDebounce<T>` custom hook in React.
Requirements:
- Accept value of generic type `T` and delay in milliseconds (default 300ms).
- Return debounced value.
- Ensure proper timer cleanup on value change or unmount to prevent memory leaks.
Act as a Senior TypeScript Developer. Refactor the following JavaScript React component to strict, error-free TypeScript code.
Requirements:
- Define explicit interfaces for all Props, State, and Event Handlers.
- Do not use `any` or `unknown` types unless strictly necessary with type guards.
- Correctly type DOM events (`React.ChangeEvent<HTMLInputElement>`, `React.FormEvent`, etc.).
[INSERT JAVASCRIPT COMPONENT CODE HERE]
Act as a TypeScript expert. Create typed React Props and Zod validation schemas for the following backend JSON response. Ensure nested objects and array elements are strongly typed with proper optionality.
[INSERT JSON RESPONSE HERE]
Create a polymorphic `Button` component in React using TypeScript.
Requirements:
- Accept dynamic `as` prop (e.g., render as `<button>`, `<a>`, or Next.js `<Link>`).
- Dynamically merge HTML attributes specific to the rendered tag using `React.ComponentPropsWithoutRef<E>`.
- Support forwarded refs (`React.forwardRef`).
Write a type-safe form handler hook wrapping React Hook Form and Zod for a user profile modification form. Infer TypeScript types automatically from the Zod schema and ensure all input fields are fully auto-completed by IDE tooling.
Act as a React Performance Engineer. Analyze the provided React component for performance bottlenecks and unnecessary re-renders.
Requirements:
- Identify objects/functions instantiated inside renders that break child component memoization.
- Apply `React.memo`, `useMemo`, and `useCallback` strategically where appropriate.
- Explain precisely WHY each optimization was applied.
[INSERT COMPONENT CODE HERE]
Refactor this heavy data processing component to optimize execution speed. Extract expensive array filtering, sorting, and aggregation calculations into `useMemo` hooks with correct dependency arrays. Explain how to avoid stale closure bugs.
[INSERT CODE HERE]
Write a React component using `@tanstack/react-virtual` (or `react-window`) to render 10,000 items efficiently in a vertical list.
Requirements:
- Set fixed container height with scroll overflow.
- Dynamic row heights support.
- Smooth scrolling rendering without UI lag or frame drops.
Demonstrate how to implement component-level code splitting on heavy React route components using `React.lazy()` and `Suspense`. Include a gracefully designed Skeleton Loader fallback UI component while dynamic modules load over the network.
Write a custom `OptimizedImage` React component in TypeScript.
Requirements:
- Native lazy loading attribute (`loading="lazy"`).
- Blurred placeholder effect until image fully downloads.
- Handle broken image URL states gracefully using fallback images.
- Support modern `<picture>` tag rendering with WebP and AVIF formats.
Act as a React QA Automation Architect. Write unit tests using Vitest and React Testing Library (`@testing-library/react`) for the following Form component.
Requirements:
- Test user typing into input fields.
- Test client-side validation error messages on empty submit.
- Test successful form submission and mock function call verification.
- Use `@testing-library/user-event` instead of `fireEvent`.
[INSERT COMPONENT CODE HERE]
Write an integration test suite for a React component that fetches user data from an API.
Requirements:
- Setup Mock Service Worker (MSW v2) REST handler.
- Test successful loading state, rendered data state, and error handling fallback when API returns HTTP 500.