15 Prompts for Creating React/Next.js Applications

15 Prompts for Creating React/Next.js Applications

Building modern React and Next.js applications often starts with a single prompt. Whether you're a seasoned frontend engineer or a newcomer to the ecosystem, having a set of battle-tested prompts can dramatically speed up your workflow. This article collects 15 specific, ready-to-use prompts for generating components, pages, data fetching logic, and more.

Why Use Prompts for React/Next.js?

Generative AI tools like ChatGPT, Claude, or GitHub Copilot can turn natural language into functional code. Instead of writing boilerplate from scratch, you describe what you need — and the AI produces a working implementation. According to a 2025 Stack Overflow survey, over 40% of developers use AI-assisted coding tools weekly. The key is crafting precise prompts that include context, constraints, and examples.

1. Generate a Functional Component with TypeScript

Prompt:

Create a React functional component named "UserCard". It should accept props: name (string), email (string), and avatarUrl (string, optional). Use TypeScript. The component should display a card with an image on the left and text on the right. Add proper styling with a CSS module.

Explanation: This prompt defines the component name, props, structure, and styling approach. It’s ideal for quickly scaffolding UI pieces.

Example output:

import styles from './UserCard.module.css';

interface UserCardProps {
  name: string;
  email: string;
  avatarUrl?: string;
}

export default function UserCard({ name, email, avatarUrl }: UserCardProps) {
  return (
    <div className={styles.card}>
      <img src={avatarUrl || '/default-avatar.png'} alt={name} className={styles.avatar} />
      <div className={styles.info}>
        <h3>{name}</h3>
        <p>{email}</p>
      </div>
    </div>
  );
}

2. Create a Next.js Page with Dynamic Routing

Prompt:

Generate a Next.js App Router page at /products/[id]. The page should fetch product data from a mock API using fetch. Handle loading state with a simple "Loading..." text. If the product is not found, display a 404 message. Use TypeScript.

Explanation: This prompt covers dynamic routes, data fetching, error handling, and loading states — essential for Next.js apps.

Example output:

// app/products/[id]/page.tsx
import { notFound } from 'next/navigation';

interface Product {
  id: number;
  name: string;
  price: number;
}

export default async function ProductPage({ params }: { params: { id: string } }) {
  const res = await fetch(`https://fakestoreapi.com/products/${params.id}`);
  if (!res.ok) notFound();
  const product: Product = await res.json();

  return (
    <div>
      <h1>{product.name}</h1>
      <p>Price: ${product.price}</p>
    </div>
  );
}

3. Build a Custom Hook for Form Handling

Prompt:

Write a custom React hook called "useForm" that manages form state. It should accept an initial values object and a validation function. Return values, errors, handleChange, and handleSubmit. The validation function should return an object with error messages. Use TypeScript generics.

Explanation: Custom hooks encapsulate logic. This prompt asks for a reusable form handler, which is a common pattern.

Example output:

import { useState, ChangeEvent, FormEvent } from 'react';

type ValidationErrors<T> = Partial<Record<keyof T, string>>;
type ValidationFn<T> = (values: T) => ValidationErrors<T>;

export function useForm<T extends Record<string, any>>(
  initialValues: T,
  validate: ValidationFn<T>
) {
  const [values, setValues] = useState<T>(initialValues);
  const [errors, setErrors] = useState<ValidationErrors<T>>({});

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setValues(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (callback: () => void) => (e: FormEvent) => {
    e.preventDefault();
    const validationErrors = validate(values);
    if (Object.keys(validationErrors).length === 0) {
      callback();
    } else {
      setErrors(validationErrors);
    }
  };

  return { values, errors, handleChange, handleSubmit };
}

4. Implement Server-Side Rendering with getServerSideProps (Pages Router)

Prompt:

Create a Next.js page using the Pages Router that uses getServerSideProps to fetch a list of blog posts from an API. Render the posts as a list. Add an error message if the fetch fails. Use TypeScript.

Explanation: SSR is critical for SEO and performance. This prompt shows how to fetch data on each request.

Example output:

// pages/blog.tsx
import { GetServerSideProps } from 'next';

interface Post {
  id: number;
  title: string;
}

interface Props {
  posts: Post[];
  error?: string;
}

export default function Blog({ posts, error }: Props) {
  if (error) return <p>Error: {error}</p>;
  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export const getServerSideProps: GetServerSideProps<Props> = async () => {
  try {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const posts: Post[] = await res.json();
    return { props: { posts } };
  } catch {
    return { props: { posts: [], error: 'Failed to fetch posts' } };
  }
};

5. Generate a Styled Button Component with Variants

Prompt:

Create a React button component that accepts variant prop: "primary", "secondary", or "danger". Use CSS-in-JS with styled-components. The button should have hover and focus states. Export as default.

Explanation: Variants are a common pattern for design systems. This prompt focuses on styling and interaction.

Example output:

import styled, { css } from 'styled-components';

interface ButtonProps {
variant?: 'primary'

| 'secondary' | 'danger';
}

const variants = {
  primary: css`background: blue; color: white;`,
  secondary: css`background: gray; color: black;`,
  danger: css`background: red; color: white;`,
};

export const Button = styled.button<ButtonProps>`
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  ${({ variant = 'primary' }) => variants[variant]}

  &:hover {
    opacity: 0.8;
  }
  &:focus {
    outline: 2px solid black;
  }
`;

6. Create a Next.js API Route with Authentication

Prompt:

Write a Next.js API route at /api/user that returns the current user's data. It should check for a valid JWT token in the Authorization header. If the token is invalid, return 401. If valid, return user info. Use the jsonwebtoken library. TypeScript.

Explanation: API routes are backend endpoints within Next.js. This prompt shows authentication middleware.

Example output:

// pages/api/user.ts (or app/api/user/route.ts for App Router)
import { NextApiRequest, NextApiResponse } from 'next';
import jwt from 'jsonwebtoken';

const SECRET = process.env.JWT_SECRET || 'your-secret';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ message: 'Unauthorized' });
  }
  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, SECRET);
    res.status(200).json({ user: decoded });
  } catch {
    res.status(401).json({ message: 'Invalid token' });
  }
}

7. Build a Search Component with Debouncing

Prompt:

Create a React search input component that debounces the onChange event by 300ms. It should accept an onSearch callback that receives the debounced query. Use TypeScript and a custom useDebounce hook.

Explanation: Debouncing prevents excessive API calls. This prompt combines a custom hook with a component.

8. Generate a Responsive Grid Layout

Prompt:

Write a React component called "ProductGrid" that renders a responsive CSS Grid with 1 column on mobile, 2 on tablet, and 4 on desktop. Pass children as props. Use CSS modules.

9. Create a Modal Component with Portal

Prompt:

Build a modal component in React that uses createPortal to render into a div with id "modal-root". It should have an overlay, close on Escape key, and accept children and onClose prop. TypeScript.

10. Implement Infinite Scroll with Intersection Observer

Prompt:

Create a custom hook "useInfiniteScroll" that triggers a callback when a sentinel element becomes visible. Use IntersectionObserver. Return a ref to attach to the sentinel. TypeScript.

11. Generate a Next.js Middleware for Redirects

Prompt:

Write Next.js middleware that redirects users from /old-blog to /blog using a 308 redirect. Also block access to /admin for non-authenticated users by checking a cookie. TypeScript.

12. Build a Tabs Component with Active State

Prompt:

Create a tabbed interface component in React. It should accept an array of tabs (label, content) and highlight the active tab. Manage state internally. Use CSS modules for styling.

13. Create a Data Table with Sorting

Prompt:

Generate a React data table component that accepts columns (key, label) and rows (array of objects). Implement click-to-sort on column headers. Use useState for sort state. TypeScript.

14. Implement a Dark Mode Toggle

Prompt:

Write a React component that toggles dark mode using CSS custom properties. Store the preference in localStorage. Use a useEffect to apply the class to the body element.

15. Generate an Error Boundary Component

Prompt:

Create a React error boundary component using class component syntax. It should catch errors in its children, display a fallback UI, and log the error to console. TypeScript.

Conclusion

These 15 prompts cover the most common tasks in React and Next.js development — from simple components to complex data fetching and authentication. By adapting these prompts to your specific project, you can save hours of manual coding. Try them out in your favorite AI tool today, and watch your productivity soar.

For more advanced patterns, refer to the official React documentation at react.dev and Next.js documentation at nextjs.org.

← All posts

Comments