AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Exporting and Organizing Stateful UI Flows from v0 into Next.js App Router

Bruno Ribeiro · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

v0 produces visually polished UI faster than any human designer-developer pairing we have tested. In sixty seconds, you can prompt a multi-step onboarding wizard, an interactive analytics dashboard with filters, or a four-stage checkout flow. The layout looks production-ready. The Tailwind utility classes are crisp. The shadcn/ui primitives slot into place effortlessly.

Then you look at the raw export, and the illusion cracks.

What v0 actually hands you is a 600-line monolithic Client Component. It is packed with in-memory useState switches, inline mock arrays, direct mutation handlers, and a blanket 'use client' directive stamped at line one. If you drop that file directly into app/onboarding/page.tsx, you break Next.js App Router's core architectural advantages: Server Component data fetching, streamable server rendering, URL-driven navigation, and granular code splitting.

At 365Finds, our engineering recommendation is categorical: treat v0 as a UI component forge, never as an application route generator. Exporting stateful flows requires a structured refactoring pipeline that separates visual presentation from state orchestration and server boundaries.


1. How v0 Exports Stateful Code

v0 offers two primary methods to pull generated code into a local repository:

# Method A: Direct component pull via v0 CLI
npx v0@latest add <component-id>

# Method B: Direct block sync via shadcn CLI (recommended)
npx shadcn@latest add "https://v0.dev/chat/b/<chat-id>?token=<token>"

Method B is the mechanism 365Finds favors. It detects your project's components.json registry file, resolves shared base primitives (like Button, Dialog, and Input) into your existing components/ui/ folder, and dumps the composite block into a dedicated file.

However, inspect what that block contains when you generate a multi-step or state-heavy interface:


2. Target Directory Structure in Next.js App Router

To prevent v0 output from polluting your route definitions, isolate the raw visual components inside a feature module before wiring them to your route segments.

Here is the folder structure 365Finds mandates for stateful UI flows:

my-app/
├── app/
│   └── (dashboard)/
│       └── onboarding/
│           ├── page.tsx               # Server Component (auth, server data fetching)
│           ├── loading.tsx            # Suspense fallback
│           └── layout.tsx             # Shared shell or persistent header
├── components/
│   ├── ui/                            # Base shadcn/ui primitives (button, card, input)
│   └── features/
│       └── onboarding/                # Feature-specific flow decomposition
│           ├── onboarding-flow.tsx    # Flow coordinator ('use client')
│           ├── step-profile.tsx       # Step 1 presentational component
│           ├── step-workspace.tsx     # Step 2 presentational component
│           ├── step-billing.tsx       # Step 3 presentational component
│           ├── flow-progress.tsx      # Visual step indicator / progress bar
│           └── types.ts               # Shared contracts, DTOs, and Zod schemas
└── lib/
    ├── actions/
    │   └── onboarding.ts              # Next.js Server Actions (mutations, DB writes)
    └── utils.ts

Notice the hard separation: app/onboarding/page.tsx contains zero visual rendering logic for the form fields. It acts strictly as an entry gate.


3. The Four-Step Refactoring Pipeline

When translating a v0 stateful flow into Next.js, follow this sequential pipeline.

Step 1: Dissect the Monolith into Pure Presentational Sub-Components

Open the exported v0 file and carve out each view state into its own file inside components/features/<flow-name>/.

For example, extract the step components so they receive data and callbacks via props rather than mutating parent state directly:

// components/features/onboarding/step-profile.tsx
'use client'

import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import type { OnboardingData } from "./types"

interface StepProfileProps {
  data: Partial<OnboardingData>
  onChange: (fields: Partial<OnboardingData>) => void
}

export function StepProfile({ data, onChange }: StepProfileProps) {
  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-xl font-semibold tracking-tight">Personal Details</h2>
        <p className="text-sm text-muted-foreground">Tell us how to identify your profile.</p>
      </div>
      <div className="space-y-2">
        <Label htmlFor="fullName">Full Name</Label>
        <Input
          id="fullName"
          value={data.fullName || ''}
          onChange={(e) => onChange({ fullName: e.target.value })}
          placeholder="Jane Doe"
        />
      </div>
    </div>
  )
}

Step 2: Elevate Flow State to the URL or a Coordinator Hook

Do not leave const [step, setStep] = useState(1) inside the UI file. 365Finds strongly advocates binding stateful multi-step progression to search parameters (?step=profile, ?step=workspace) or route segments. URL state enables back-button navigation, bookmarking, and link sharing.

Using Next.js native useSearchParams and useRouter:

// components/features/onboarding/onboarding-flow.tsx
'use client'

import { useSearchParams, useRouter } from "next/navigation"
import { useState, useTransition } from "react"
import { StepProfile } from "./step-profile"
import { StepWorkspace } from "./step-workspace"
import { FlowProgress } from "./flow-progress"
import { Button } from "@/components/ui/button"
import type { OnboardingData } from "./types"

const STEPS = ['profile', 'workspace', 'billing'] as const
type Step = typeof STEPS[number]

export function OnboardingFlow({ initialUser }: { initialUser: { email: string } }) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [isPending, startTransition] = useTransition()

  const currentStep = (searchParams.get("step") as Step) || "profile"
  const [formData, setFormData] = useState<Partial<OnboardingData>>({
    email: initialUser.email
  })

  function updateStep(nextStep: Step) {
    const params = new URLSearchParams(searchParams.toString())
    params.set("step", nextStep)
    startTransition(() => {
      router.push(`?${params.toString()}`)
    })
  }

  function handleDataChange(patch: Partial<OnboardingData>) {
    setFormData((prev) => ({ ...prev, ...patch }))
  }

  return (
    <div className="mx-auto max-w-xl space-y-8 py-10">
      <FlowProgress currentStep={currentStep} steps={STEPS} />

      <div className="rounded-lg border bg-card p-6 shadow-sm">
        {currentStep === "profile" && (
          <StepProfile data={formData} onChange={handleDataChange} />
        )}
        {currentStep === "workspace" && (
          <StepWorkspace data={formData} onChange={handleDataChange} />
        )}

        <div className="mt-8 flex justify-between">
          <Button
            variant="outline"
            disabled={currentStep === "profile" || isPending}
            onClick={() => updateStep(currentStep === "workspace" ? "profile" : "workspace")}
          >
            Back
          </Button>

          {currentStep === "profile" && (
            <Button onClick={() => updateStep("workspace")}>Continue</Button>
          )}
        </div>
      </div>
    </div>
  )
}

Step 3: Replace Synthetic Mock Data with Server Actions

v0 generates forms with placeholder submit handlers like onSubmit={(e) => { e.preventDefault(); console.log(data) }}.

Replace this with a typed Next.js Server Action located in lib/actions/onboarding.ts. Validate payloads server-side using Zod before mutating the database:

// lib/actions/onboarding.ts
'use server'

import { z } from "zod"
import { revalidatePath } from "next/cache"
import { redirect } from "next/navigation"

const OnboardingSchema = z.object({
  fullName: z.string().min(2),
  workspaceName: z.string().min(3),
})

export async function completeOnboarding(formData: unknown) {
  const validated = OnboardingSchema.safeParse(formData)
  if (!validated.success) {
    return { error: validated.error.flatten().fieldErrors }
  }

  // Execute database mutation (e.g. Prisma / Drizzle)
  // await db.user.update(...)

  revalidatePath("/dashboard")
  redirect("/dashboard")
}

Step 4: Keep the Route Page a Server Component

The page file (app/(dashboard)/onboarding/page.tsx) must remain an asynchronous Server Component. It queries the session or server data source directly, handles unauthenticated redirects, and passes initial properties into the client flow coordinator:

// app/(dashboard)/onboarding/page.tsx
import { redirect } from "next/navigation"
import { OnboardingFlow } from "@/components/features/onboarding/onboarding-flow"

// Server-side auth verification and initial data retrieval
async function getSessionUser() {
  // Direct server-side call or database lookup
  return { email: "alex@example.com", id: "usr_102" }
}

export default async function OnboardingPage() {
  const user = await getSessionUser()
  if (!user) {
    redirect("/login")
  }

  return (
    <main className="min-h-screen bg-muted/40">
      <OnboardingFlow initialUser={user} />
    </main>
  )
}

4. Key Architectural Trade-Offs

DecisionMonolithic v0 Export365Finds Refactored Architecture
Component Boundary100% Client-side ('use client')Server Component page + targeted Client Islands
Step NavigationIn-memory useState (breaks browser Back/Refresh)URL Search Params (?step=) or nested route segments
Data FetchingClient-side useEffect or static mocksDirect server DB query inside page.tsx
Data MutationInline event handlers (console.log)Typed Server Actions with server-side Zod validation
Maintainability500+ lines in one fileModular subcomponents grouped under components/features/

5. Practical Traps When Importing v0 into Next.js

  1. Radix Primitive Version Conflicts: v0 generates components using specific releases of @radix-ui/react-*. If your Next.js project has existing shadcn components, running npx shadcn@latest add can occasionally update or conflict with peer dependencies. Lock your package versions in package.json.
  2. Missing Utility Functions: v0 output relies on the standard shadcn cn() helper (clsx + tailwind-merge). Ensure your path alias @/lib/utils is configured in tsconfig.json.
  3. Over-splitting State: Avoid putting every single text field into separate global Zustand or Redux slices. Keep transient form state inside the feature coordinator (onboarding-flow.tsx), elevate flow progression to URL search parameters, and reserve server actions for step completions.

v0 accelerates the most tedious phase of front-end engineering: assembling accessible, responsive component trees. But bridging the gap from a visual prototype to a production Next.js App Router application requires deliberate boundary enforcement. Put the layout in components/features/, drive the flow via the URL, and keep your page.tsx firmly on the server.

References