Books/React & Next.js Essentials/React & Next.js Cheat Sheet

    React & Next.js Cheat Sheet

    React & Next.js Cheat Sheet

    Your complete quick reference for building React and Next.js applications — with ready-to-use AI prompts for every common task. Bookmark this page!

    React Component Patterns

    // Basic component
    function MyComponent() {
      return <div>Hello</div>;
    }
    
    // Component with props
    interface CardProps {
      title: string;
      children: React.ReactNode;
      variant?: "default" | "outlined";
    }
    
    const Card = ({ title, children, variant = "default" }: CardProps) => (
      <div className={variant === "outlined" ? "border rounded p-4" : "bg-white shadow rounded p-4"}>
        <h2 className="font-bold text-lg">{title}</h2>
        {children}
      </div>
    );
    
    // List rendering
    const UserList = ({ users }: { users: User[] }) => (
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    );
    
    // Conditional rendering
    const Alert = ({ show, message }: { show: boolean; message: string }) => (
      show ? <div className="bg-red-100 text-red-800 p-3 rounded">{message}</div> : null
    );

    Common Hook Patterns

    import { useState, useEffect, useRef } from "react";
    
    // ── useState ──
    const [value, setValue] = useState("");                    // String
    const [count, setCount] = useState(0);                    // Number
    const [open, setOpen] = useState(false);                  // Boolean
    const [user, setUser] = useState<User | null>(null);      // Nullable object
    const [items, setItems] = useState<Item[]>([]);           // Array
    const [form, setForm] = useState({ name: "", email: "" });// Object
    
    // Update patterns
    setCount(prev => prev + 1);                               // Based on previous
    setItems(prev => [...prev, newItem]);                     // Add to array
    setItems(prev => prev.filter(i => i.id !== id));          // Remove from array
    setForm(prev => ({ ...prev, name: "Alice" }));            // Update object field
    
    // ── useEffect ──
    useEffect(() => { /* runs every render */ });
    useEffect(() => { /* runs once on mount */ }, []);
    useEffect(() => { /* runs when deps change */ }, [userId, page]);
    useEffect(() => {
      const timer = setInterval(() => {}, 1000);
      return () => clearInterval(timer);  // Cleanup
    }, []);
    
    // ── useRef ──
    const inputRef = useRef<HTMLInputElement>(null);
    inputRef.current?.focus();                                // Access DOM
    const countRef = useRef(0);                               // Mutable value (no re-render)

    Data Fetching Patterns

    // ── Server Component (default in Next.js App Router) ──
    export default async function Page() {
      const data = await fetch("https://api.example.com/data").then(r => r.json());
      return <div>{data.title}</div>;
    }
    
    // ── Client Component ──
    "use client";
    function ClientPage() {
      const [data, setData] = useState<Data | null>(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState<string | null>(null);
    
      useEffect(() => {
        fetch("/api/data")
          .then(res => res.json())
          .then(setData)
          .catch(err => setError(err.message))
          .finally(() => setLoading(false));
      }, []);
    
      if (loading) return <Skeleton />;
      if (error) return <Error message={error} />;
      return <Display data={data} />;
    }
    
    // ── Custom hook ──
    function useFetch<T>(url: string) {
      const [data, setData] = useState<T | null>(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState<string | null>(null);
    
      useEffect(() => {
        fetch(url)
          .then(r => r.json()).then(setData)
          .catch(e => setError(e.message))
          .finally(() => setLoading(false));
      }, [url]);
    
      return { data, loading, error };
    }

    Next.js File Structure

    my-app/
    ├── app/
    │   ├── layout.tsx            Root layout (header, footer)
    │   ├── page.tsx              Home page (/)
    │   ├── loading.tsx           Global loading UI
    │   ├── error.tsx             Global error UI
    │   ├── not-found.tsx         404 page
    │   ├── globals.css           Global styles
    │   ├── about/
    │   │   └── page.tsx          /about
    │   ├── blog/
    │   │   ├── page.tsx          /blog
    │   │   └── [slug]/
    │   │       └── page.tsx      /blog/:slug
    │   ├── dashboard/
    │   │   ├── layout.tsx        Dashboard layout (sidebar)
    │   │   ├── page.tsx          /dashboard
    │   │   └── settings/
    │   │       └── page.tsx      /dashboard/settings
    │   └── api/
    │       └── users/
    │           └── route.ts      API: /api/users
    ├── components/
    │   ├── ui/                   shadcn/ui components
    │   ├── Navbar.tsx            Shared components
    │   └── Footer.tsx
    ├── lib/
    │   └── utils.ts              Utility functions
    ├── public/                   Static files (images, fonts)
    ├── tailwind.config.ts        Tailwind configuration
    ├── next.config.js            Next.js configuration
    └── package.json
    

    Next.js Special Files

    FilePurposeExample
    page.tsxPage contentHome page, about page
    layout.tsxPersistent wrapperHeader + sidebar + footer
    loading.tsxLoading skeletonShown while page data loads
    error.tsxError boundary"Something went wrong" UI
    not-found.tsx404 page"Page not found" UI
    route.tsAPI endpointREST API handlers
    template.tsxRe-mounting wrapperAnimations on route change

    Next.js Routing Quick Reference

    // Static route
    // app/about/page.tsx → /about
    
    // Dynamic route
    // app/blog/[slug]/page.tsx → /blog/my-post
    export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
      const { slug } = await params;
      return <div>{slug}</div>;
    }
    
    // Navigation
    import Link from "next/link";
    <Link href="/about">About</Link>
    <Link href={`/blog/${post.slug}`}>{post.title}</Link>
    
    // Programmatic navigation
    "use client";
    import { useRouter } from "next/navigation";
    const router = useRouter();
    router.push("/dashboard");
    router.back();

    Tailwind CSS Quick Reference

    Layout

    ClassEffect
    flexFlexbox container
    flex-colVertical flex
    items-centerAlign items vertically
    justify-betweenSpace between items
    justify-centerCenter items horizontally
    gap-4Gap between items (16px)
    grid grid-cols-33-column grid
    w-fullFull width
    max-w-mdMax width: 448px
    mx-autoCenter horizontally
    hidden md:blockHide on mobile, show on tablet+

    Spacing

    ClassEffect
    p-4Padding: 16px all sides
    px-6 py-3Horizontal: 24px, Vertical: 12px
    m-4Margin: 16px all sides
    mt-8Margin top: 32px
    space-y-4Vertical space between children

    Typography

    ClassEffect
    text-smSmall text (14px)
    text-lgLarge text (18px)
    text-2xlExtra large (24px)
    text-4xlHeading size (36px)
    font-boldBold weight
    font-semiboldSemi-bold weight
    text-gray-600Gray text
    text-centerCenter aligned

    Colors & Borders

    ClassEffect
    bg-whiteWhite background
    bg-gray-100Light gray background
    bg-blue-500Blue background
    text-gray-900Dark text
    border1px border
    border-gray-200Light gray border
    roundedSmall border radius
    rounded-lgLarge border radius
    shadow-smSmall shadow
    shadow-lgLarge shadow

    States & Responsive

    ClassEffect
    hover:bg-blue-600Darker on hover
    focus:ring-2Ring on focus
    active:scale-95Scale down on press
    disabled:opacity-50Dim when disabled
    dark:bg-gray-900Dark mode background
    md:grid-cols-22 columns on tablet+
    lg:text-xlLarger text on desktop

    AI Prompts for React & Next.js Development

    Starting a Project

    • "Create a new Next.js app with TypeScript, Tailwind CSS, and shadcn/ui. Set up the folder structure with a home page, about page, and dashboard section."
    • "Set up a Next.js project with authentication using [NextAuth/Clerk/Firebase Auth]. Include login, signup, and protected routes."
    • "Initialize a React project with Vite, TypeScript, Tailwind, and React Router. Create a basic layout with header and footer."

    Building Components

    • "Create a responsive navigation bar with a logo, links, and a mobile hamburger menu. Use Tailwind and shadcn/ui."
    • "Build a product card component that shows image, title, price, and an Add to Cart button. Make it responsive."
    • "Create a modal/dialog component using shadcn/ui. It should open on button click and close on backdrop click or Escape."
    • "Build a multi-step form with validation. Step 1: personal info. Step 2: preferences. Step 3: confirmation."

    Data & State Management

    • "Fetch a list of [items] from /api/[items] in a Server Component and display them in a responsive grid."
    • "Create a search page with debounced input. Fetch results from /api/search?q= as the user types."
    • "Build a shopping cart using React Context. Support add, remove, update quantity, and calculate total."
    • "Create a custom hook called useAsync that handles loading, error, and data states for any async function."

    Pages & Layouts

    • "Create a dashboard layout with a sidebar, top bar, and main content area. The sidebar should collapse on mobile."
    • "Build a blog with a list page showing post previews and a dynamic [slug] page showing the full post."
    • "Set up a settings page with tabs for Profile, Account, Notifications, and Billing."
    • "Create a landing page with hero section, features grid, testimonials, pricing cards, and footer."

    Styling & Polish

    • "Add dark mode support to this component. Use Tailwind's dark: prefix."
    • "Make this layout fully responsive. On mobile: single column. Tablet: two columns. Desktop: three columns with sidebar."
    • "Add loading skeletons that match the layout of the actual content."
    • "Add smooth page transitions using Framer Motion."

    Debugging React

    • "This component re-renders too many times. Here's the code: [paste]. How do I optimize it?"
    • "I'm getting 'Cannot read property of null'. Here's my component: [paste]. What's causing it?"
    • "My useEffect runs in an infinite loop. Here's the code: [paste]. What's wrong with the dependencies?"
    • "State isn't updating when I click the button. Here's my handler: [paste]. What am I doing wrong?"

    The Development Workflow

    1. PLAN    → Describe what you want to the AI (be specific!)
    2. BUILD   → AI generates components, pages, and logic
    3. REVIEW  → Read the code — check components, props, state, routing
    4. STYLE   → Adjust Tailwind classes for the look you want
    5. TEST    → Run the app, click through everything
    6. ITERATE → Tell the AI what to change, fix, or add
    

    Tips for better AI prompts:

    • Be specific about what data the component shows
    • Mention which library/framework to use (Next.js, shadcn/ui, Tailwind)
    • Describe the responsive behavior you want
    • Include error and loading states in your requirements
    • Reference existing components: "Use the same card style as the products page"

    Remember: You don't need to memorize all of this. Use this page as a reference, and let AI tools handle the implementation details. Your job is to describe what you want clearly and review what you get back.

    Happy building!


    🌐 www.genai-mentor.ai