10 Prompts for Building React & Next.js Applications Like a Pro

Introduction

Building modern frontend applications with React and Next.js involves repetitive tasks – creating components, setting up routing, handling state, writing tests. Instead of starting from scratch every time, you can use well-crafted prompts to generate reliable, production‑ready code in seconds. Whether you're a seasoned developer or just starting out, these prompts will speed up your workflow and enforce best practices.

Below I’ve curated 10 prompts that cover the most common scenarios in React and Next.js development. Each prompt is a template you can copy, paste, and adjust to your needs. I’ve also included a real usage example and the actual code output so you can see exactly what to expect.


1. Generate a Functional React Component with TypeScript

Prompt:

Create a functional React component named {ComponentName} that accepts {prop1}: {type1} and {prop2}: {type2}. Use TypeScript interfaces for the props. Include a brief description of what the component does. Export the component as default.

Explanation: This prompt forces you to think about the component’s contract (props) and its purpose. It’s ideal for quickly scaffolding UI elements like buttons, cards, or modals.

Example usage:
*Replace placeholders:* Button, label: string, onClick: () => void

Generated code:

interface ButtonProps {
  label: string;
  onClick: () => void;
}

const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
  return <button onClick={onClick}>{label}</button>;
};

export default Button;

Source: React TypeScript Cheatsheet


2. Create a Next.js Page with Dynamic Routes

Prompt:

Generate a Next.js page located at /{route}/[id].tsx that fetches data from {API endpoint} using getServerSideProps. The page should display the title and body of the fetched item. Handle 404 errors with a custom notFound message.

Explanation: Dynamic routing is a core Next.js feature. This prompt sets up server‑side rendering and error handling, which is critical for SEO and user experience.

Example usage:
*posts/[id].tsx, endpoint https://jsonplaceholder.typicode.com/posts/${id}*

Generated code:

// pages/posts/[id].tsx
import { GetServerSideProps } from 'next';

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

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { id } = context.params!;
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
  if (!res.ok) return { notFound: true };
  const post: Post = await res.json();
  return { props: { post } };
};

const PostPage: React.FC<{ post: Post }> = ({ post }) => {
  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </article>
  );
};

export default PostPage;

Source: Next.js Dynamic Routes Documentation


3. Design a Custom React Hook for Data Fetching

Prompt:

Write a custom React hook called use{Name} that takes a URL as a parameter. It should return { data, loading, error }. Use useEffect and useState. Include a cleanup function to avoid setting state on unmounted components.

Explanation: Custom hooks encapsulate reusable logic. This pattern is ubiquitous in React apps for fetching data from APIs.

Example usage:
*useFetch, URL 'https://api.example.com/users'*

Generated code:

import { useState, useEffect } from 'react';

export function useFetch<T>(url: string) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(json => { if (!cancelled) setData(json); })
      .catch(err => { if (!cancelled) setError(err); })
      .finally(() => { if (!cancelled) setLoading(false); });

    return () => { cancelled = true; };
  }, [url]);

  return { data, loading, error };
}

Source: React useEffect Recipe – Data Fetching


4. Build a Responsive Navbar Component in React

Prompt:

Create a responsive Navbar component using CSS modules (or Styled Components). The navbar should have a logo on the left, navigation links in the center, and a “Get Started” button on the right. On mobile (<768px), the links should collapse into a hamburger menu. Use React state to toggle the menu.

Explanation: Responsive navigation is a common UI pattern. This prompt covers state management and conditional rendering.

Example usage:
*With CSS modules (Navbar.module.css)*

Generated code (simplified):

import { useState } from 'react';
import styles from './Navbar.module.css';

const Navbar = () => {
  const [menuOpen, setMenuOpen] = useState(false);

  return (
    <nav className={styles.navbar}>
      <div className={styles.logo}>Logo</div>
      <ul className={`${styles.links} ${menuOpen ? styles.active : ''}`}>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
        <li><a href="/contact">Contact</a></li>
      </ul>
      <button className={styles.cta}>Get Started</button>
      <button className={styles.hamburger} onClick={() => setMenuOpen(!menuOpen)}>
        ☰
      </button>
    </nav>
  );
};

export default Navbar;

CSS (partial):

.navbar { display: flex; align-items: center; justify-content: space-between; }
.links { display: flex; gap: 1rem; }
.hamburger { display: none; }
@media (max-width: 768px) {
  .links { display: none; &.active { display: flex; flex-direction: column; } }
  .hamburger { display: block; }
}

5. Generate a Next.js API Route with Error Handling

Prompt:

Create an API route at pages/api/{name}.ts that handles GET requests. It should connect to a database (or a mock data source) and return the list of {items}. Use try/catch and return proper HTTP status codes (200, 500).

Explanation: API routes are a core Next.js feature for building backend logic within the same project. Error handling ensures reliability.

Example usage:
*products, mock data from a local array*

Generated code:

// pages/api/products.ts
import type { NextApiRequest, NextApiResponse } from 'next';

type Product = { id: number; name: string; price: number };

const products: Product[] = [
  { id: 1, name: 'Widget', price: 9.99 },
  { id: 2, name: 'Gadget', price: 19.99 },
];

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'GET') {
    return res.status(405).json({ message: 'Method not allowed' });
  }

  try {
    res.status(200).json(products);
  } catch (error) {
    res.status(500).json({ message: 'Internal server error' });
  }
}

Source: Next.js API Routes


6. Create a React Context Provider for State Management

Prompt:

Define a React context called {ContextName} and a Provider component. The context should provide {stateValue} and a {setStateValue} function. Wrap the children with the Provider. Export the context and a custom hook use{ContextName}.

Explanation: Context + hooks is a lightweight state management solution, perfect for themes, authentication, or global settings.

Example usage:
*ThemeContext, theme and setTheme*

Generated code:

import React, { createContext, useContext, useState, ReactNode } from 'react';

interface ThemeContextType {
  theme: 'light' | 'dark';
  setTheme: (theme: 'light' | 'dark') => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error('useTheme must be used inside ThemeProvider');
  return ctx;
};

Source: React Context Documentation


7. Optimize a React Component with useMemo and useCallback

Prompt:

Optimize the following component by wrapping expensive computations in useMemo and callback functions in useCallback. Explain the dependencies array.

Explanation: Performance optimization is essential for large lists or complex calculations. This prompt teaches memoization.

Example implementation (user provides component):

Generated code snippet:

import React, { useMemo, useCallback } from 'react';

const ExpensiveList: React.FC<{ items: number[]; onItemClick: (id: number) => void }> = ({ items, onItemClick }) => {
  const doubledItems = useMemo(() => items.map(item => item * 2), [items]);
  const handleClick = useCallback((id: number) => {
    onItemClick(id);
  }, [onItemClick]);

  return (
    <ul>
      {doubledItems.map(item => (
        <li key={item} onClick={() => handleClick(item)}>{item}</li>
      ))}
    </ul>
  );
};

Source: React useMemo and useCallback


8. Generate a Next.js Middleware for Authentication

Prompt:

Write a Next.js middleware (middleware.ts in the root) that checks for a cookie named {authCookie}. If the cookie is missing and the request is to a protected route (e.g., /dashboard/*), redirect to /login. Otherwise, allow the request.

Explanation: Middleware runs before every request, making it ideal for authentication guards, redirects, and header manipulation.

Example usage:
*Cookie name session*

Generated code:

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const session = request.cookies.get('session');
  const { pathname } = request.nextUrl;

  if (!session && pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*'],
};

Source: Next.js Middleware Documentation


9. Write Unit Tests for a React Component using Jest and React Testing Library

Prompt:

Write unit tests for a {ComponentName} that renders a button with a label. Test that the button fires the onClick handler, and that the label text is rendered correctly. Use Jest and @testing-library/react.

Explanation: Testing is crucial for maintaining code quality. This prompt provides a starting point for component tests.

Example usage:
*Button component as in prompt #1*

Generated code:

import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders button with label', () => {
  render(<Button label="Click me" onClick={() => {}} />);
  expect(screen.getByText('Click me')).toBeInTheDocument();
});

test('fires onClick when clicked', () => {
  const handleClick = jest.fn();
  render(<Button label="Click" onClick={handleClick} />);
  fireEvent.click(screen.getByText('Click'));
  expect(handleClick).toHaveBeenCalledTimes(1);
});

Source: React Testing Library Documentation


10. Build a Form with Validation using React Hook Form

Prompt:

Build a registration form with fields: name (required, min 2 chars), email (required, valid email), password (required, min 8 chars). Use react-hook-form with zod resolver for validation. On submit, log the data to the console. Show error messages below each field.

Explanation: Forms are a common pain point. React Hook Form + Zod provides a performant, type‑safe solution.

Example usage:

Generated code:

import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';

const schema = z.object({
  name: z.string().min(2, 'Name must be at least 2 characters'),
  email: z.string().email('Invalid email'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
});

type FormData = z.infer<typeof schema>;

export default function RegisterForm() {
  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  const onSubmit = (data: FormData) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>Name:</label>
        <input {...register('name')} />
        {errors.name && <p>{errors.name.message}</p>}
      </div>
      <div>
        <label>Email:</label>
        <input {...register('email')} />
        {errors.email && <p>{errors.email.message}</p>}
      </div>
      <div>
        <label>Password:</label>
        <input type="password" {...register('password')} />
        {errors.password && <p>{errors.password.message}</p>}
      </div>
      <button type="submit">Register</button>
    </form>
  );
}

Source: React Hook Form Documentation, Zod Documentation


Conclusion

These 10 prompts cover the majority of daily tasks in React and Next.js development. By turning them into reusable templates, you save time and reduce bugs. Copy them into your favorite AI tool, adjust the placeholders, and watch as production‑ready code appears.

Next step: Start your next project and use these prompts as a checklist. You’ll be amazed how fast you can scaffold an entire feature. If you have a specific scenario not covered here, tweak the patterns – the principles remain the same.

Happy coding!

← All posts

Comments