A deep dive into designing a drag-and-drop form builder with normalized state, conditional logic, field-dependent validation, and a dual-surface architecture that keeps the builder and respondent renderer in sync.
FrontendX EngineeringSystem Design Series
1. Requirements & Scoping
Building a no-code form builder means designing two entirely different applications that share the same data: a builder where someone drags, drops, and configures fields, and a renderer where respondents fill in and submit. The hardest part is not the drag and drop — it is keeping the builder state, the preview, and the live renderer all reading from exactly one source of truth without writing the same logic three times.
Key Insight
A no-code builder is genuinely two products in one trench coat. The builder mutates a schema; the renderer reads and validates it. On top of that, conditional logic means the renderer is running a tiny rule engine on every keystroke. The data model has to serve both masters.
Functional
Drag fields from a palette onto a canvas to build a form
Supported field types: short text, paragraph, multiple choice, checkboxes, dropdown, linear scale, date
Reorder fields by dragging within the canvas; click a field to open a settings panel
Conditional logic — show or hide a field based on the answer to a previous field
Live preview updates as you build
Publish a form, get a shareable link, collect responses, and view them in a table
Non-Functional
Sub-50ms builder interactions — no lag while dragging or typing a label
Respondent view loads under 2s on mobile — SSR for first paint
Builder bundle under 150KB gzipped; respondent bundle under 40KB
Accessibility: WCAG 2.1 AA for both builder and respondent view
Cross-browser: Chrome, Firefox, Safari, Edge — including touch for tablet builders
Tip
The respondent view is the thing that needs to be fast. Nobody abandons a form because the builder was slow — they abandon because the loading spinner on the respondent page took too long. That is why we SSR the renderer and CSR the builder.
Out of Scope
We are not covering multi-language support, file upload fields, payment integrations, or enterprise SSO — those are separate modules and each deserves its own article.
2. Architecture — Two Surfaces, One Schema
The defining architectural decision is how to split the builder and the renderer. These are not two features — they are two different applications. The builder is an authenticated workspace with heavy UI (drag and drop, settings panels, color pickers). The renderer is a public-facing form that needs to load fast and work on mobile.
Typeform and SurveyMonkey both use SSR for the respondent view and CSR for the builder. Google Forms, on the other hand, renders the respondent view entirely on the client — which works because Google's infrastructure makes the initial load fast anyway, but the first paint is still slower than a rendered HTML response.
We split the application into four Next.js routes:
example.ts
/ → Dashboard — list of all your forms
/forms/new → Creates a new form and redirects to /forms/[id]/edit
/forms/[id]/edit → Builder view (CSR) — authenticated
/forms/[id]/view → Respondent renderer (SSR) — public
/forms/[id]/responses → Response table (CSR) — authenticated
This split means the builder never pays the SSR cost, and respondents get fast first paint without us building two separate applications. The key insight: both surfaces read from the same FormSchema — the builder mutates it, the preview reads it, and the renderer consumes it. One data model, two interaction modes.
Dual-surface architecture — builder (CSR) and renderer (SSR) share the same schema through a Zustand store, served through separate routes
Component Structure
The builder has three visual zones that mirror the three concerns in the code:
example.ts
<BuilderPage>
├── <FieldPalette /> ← static list of draggable field types
├── <FormCanvas /> ← the live form being built; drop target
│ └── <FieldCard /> ← one field; also a drag source for reordering
└── <FieldSettingsPanel /> ← appears when a field is selected
<RendererPage>
├── <FormHeader /> ← title and description
├── <FieldRenderer /> ← iterates visible fields, applies conditional rules
│ └── <[FieldType] /> ← TextInput, MultipleChoice, DatePicker, etc.
└── <SubmitButton />
The FieldRenderer does not know about the builder at all. It receives a formSchema and an answers object, and it computes which fields to show. This separation makes the renderer reusable — we use the same component in the live preview panel inside the builder and in the public respondent view, with no changes.
Framework and State Management
We use React with Zustand for the builder and React Hook Form for the respondent renderer. These two libraries serve very different jobs. The builder has complex, deeply nested state — a list of fields, each with its own settings, conditional rules, and UI state like selectedFieldId. Zustand's flat store model handles this well because we can update a single field by ID without touching the rest of the list.
React Hook Form, on the other hand, is built for the renderer. It keeps each field's value and validation state local to that field and only triggers re-renders for the components that actually changed. A respondent typing in field 3 should not re-render field 7.
Approach
State Updates
Bundle Size
Best For
Zustand
~5ms per field update
~1KB gzip
Builder — frequent nested mutations
React Context
~220ms per field update
0KB (built-in)
Simple apps, <10 fields
Redux
~45ms + middleware overhead
~8KB gzip
Large teams, complex async workflows
Jotai
~35ms per atom update
~2KB gzip
Fine-grained subscriptions
Note
Complex form applications using Jotai show average state update times of 35ms, compared to 220ms with React Context. In a builder where every drag tick fires a state change, that gap is the difference between smooth and stuttery. We chose Zustand because its direct mutation model with Immer is the simplest for the builder's nested state shape.
3. Data Model — Normalized Field State
The data model is the most consequential decision in a form builder. The naive approach is an array of field objects — it looks simple but breaks down the moment the user types in a field label. Every keypress produces a new array, and every component that reads state.fields re-renders, even though 49 of the 50 fields are identical. On a large form this causes visible lag in the label input.
Normalized State: byIds + allIds + childOrder
Normalized state splits the data into three pieces. byIds is a plain object map from field ID to field data — updating one field only changes that field's entry. allIds is an ordered array of IDs that controls the sequence. childOrder maps section IDs to their child field IDs for nesting.
example.ts
interface FieldsState {
byIds: Record<string, FormField>; // O(1) lookup and update
allIds: string[]; // top-level render order
childOrder: Record<string, string[]>; // sectionId → child field IDs
}
// Updating one field — only that entry changes
state.fields.byIds[targetId] = { ...state.fields.byIds[targetId], label: newLabel };
// Reordering — only allIds changes, byIds untouched
const newAllIds = [...state.fields.allIds];
const [moved] = newAllIds.splice(fromIndex, 1);
newAllIds.splice(toIndex, 0, moved);
state.fields.allIds = newAllIds;
Normalized state with byIds, allIds, and childOrder — computed views derive visible fields without scanning the entire tree
The FormField Schema
example.ts
interface FormField {
id: string; // e.g. "field_7x3q"
type: FieldType; // "shortText" | "paragraph" | "multipleChoice"
// | "checkboxes" | "dropdown" | "linearScale"
// | "date" | "section"
label: string; // "What is your name?"
description: string; // optional helper text
required: boolean; // respondent must answer
placeholder: string; // for text fields
options: string[]; // for multipleChoice, checkboxes, dropdown
scaleMin: number; // for linearScale
scaleMax: number;
scaleMinLabel: string;
scaleMaxLabel: string;
parentId: string | null; // null = top-level; section ID = nested
conditionalRule: ConditionalRule | null;
validation: FieldValidation;
conditionalValidation: ConditionalValidationRule[];
}
Notice parentId. This single field is what allows nesting without abandoning the flat byIds structure. Every field that lives inside a section points to that section's ID via parentId. Top-level fields have parentId: null. We never store children arrays inside parents — that would bring back the nested-update problem we just avoided.
Each field owns its own rule rather than storing all rules in a central list. When we delete a field we delete its rule automatically. The conditionalValidation array is what enables field-dependent validation — where a dropdown shows different options depending on what the respondent answered in a previous field.
The Full FormSchema
example.ts
interface FormSchema {
id: string;
title: string;
description: string;
fields: FieldsState;
createdAt: string;
updatedAt: string;
publishedAt: string | null; // null = draft; respondent URL only works when set
}
Note
publishedAt is the gatekeeper for the respondent view. The server checks this field before rendering — a draft form returns 404 for the respondent route. Publishing is a one-way toggle (you can unpublish but existing respondent links break).
Accessor Helpers
Rather than sprinkling state.fields.byIds[id] everywhere, we write a small set of helpers:
example.ts
function getField(fields: FieldsState, id: string) {
return fields.byIds[id];
}
function getTopLevelIds(fields: FieldsState) {
return fields.allIds;
}
function getChildrenIds(fields: FieldsState, sectionId: string) {
return fields.childOrder[sectionId] ?? [];
}
function getLeafFieldIds(fields: FieldsState) {
return fields.allIds.flatMap((id) => {
const field = fields.byIds[id];
if (field.type === "section") {
return fields.childOrder[id] ?? [];
}
return [id];
});
}
getLeafFieldIds is what the respondent renderer calls. It flattens sections out and returns only the actual input fields in the correct top-to-bottom order. The renderer does not need to know about the section structure at all.
The Zustand Store
The builder stores the form schema and a separate selectedFieldId that tracks which field the user clicked. This UI state is not saved to the server — it lives only in the browser tab.
We use Zustand with Immer, which lets us write mutations directly on a draft object. The splice and delete calls above look like they mutate state directly, but Immer intercepts them and produces a new immutable state behind the scenes.
Key Insight
The normalized pattern (byIds + allIds) is the single most impactful optimization for a form builder. It turns a 50-field re-render into a 1-field re-render on every label edit. Without this, even a simple form feels sluggish. With it, a 200-field form feels as fast as a 5-field one.
4. Interface Definition (API)
The REST API mirrors the data model directly. Each endpoint operates on either the entire form schema or individual fields. The key design choice: we send only changed fields, not the full schema on every save.
REST Endpoints
example.ts
POST /api/forms
→ Body: { title: string }
→ Response: { id, title, fields: { byIds: {}, allIds: [] }, publishedAt: null }
PUT /api/forms/:id
→ Body: Partial<FormSchema> // only changed fields
→ Response: { updatedAt: string }
GET /api/forms/:id/published
→ Response: FormSchema // only if publishedAt is set, else 404
POST /api/forms/:id/responses
→ Body: { answers: Record<string, string | string[]>, submittedAt: string }
→ Response: { responseId: string }
GET /api/forms/:id/responses?page=1&limit=50
→ Response: { total: number, responses: Array<{ id, submittedAt, answers }> }
Component Interfaces
The FieldCard is the most reused component — it appears in the canvas during building and in the preview panel. It does not fetch data. It receives everything through props and fires events upward.
Notice allFields in the settings panel props. The conditional rule editor needs to show a dropdown of all other fields so the user can pick which one to check. We pass the full list as a prop rather than reading the store inside the panel — this makes the panel testable without a store.
5. Drag & Drop Builder
The drag and drop layer is where the builder earns its name. Three things need to work together: dragging fields from the palette onto the canvas, reordering fields within the canvas, and nested drag-and-drop for sections.
Library Choice: DnD Kit
Library
Touch Support
Maintained
Keyboard DnD
Bundle
DnD Kit
First-class
Yes
Built-in
~15KB
react-beautiful-dnd
Yes
No (archived 2024)
Manual
~20KB
React DnD
Poor (HTML5 backend)
Yes
Manual
~12KB + adapter
Jotform open-sourced their dnd-builder React library, and it uses a similar headless approach — letting the product team own the visual layer completely while the library owns the interaction model. DnD Kit is the best fit because it is headless (it handles logic, not styling), has first-class accessibility with keyboard navigation built in, and works on both mouse and touch with the same API.
One important DnD Kit pattern: track activeId and render it inside DragOverlay rather than in-place. This prevents the list from jumping as the dragged item leaves its original slot.
Nested DnD for Sections
Each SectionCard creates its own nested DndContext. This scopes drag so that dragging a field inside section 1 cannot accidentally drop it into section 2's order list. DnD Kit supports nested contexts natively.
One UX detail: users cannot tell where a dragged field will land without a visual indicator. We add a thin line between fields that lights up during drag:
The insertion indicator is the difference between a drag and drop experience that feels precise and one that feels like guessing. Jotform's open source dnd-builder library documents this exact pattern. Without it, users drop fields in the wrong spot and have to reorder again.
6. Conditional Logic & Dynamic Validation
This is where the form builder goes from a simple form creator to a powerful survey tool. We have two layers working together: visibility (should this field even be rendered?) and constrained validation (if it is rendered, what values are valid given the context?).
Field Visibility Engine
example.ts
function isFieldVisible(
field: FormField,
answers: Record<string, string | string[]>
): boolean {
if (!field.conditionalRule) return true;
const { sourceFieldId, operator, value } = field.conditionalRule;
const sourceAnswer = answers[sourceFieldId];
if (operator === "isEmpty") return !sourceAnswer || sourceAnswer.length === 0;
if (operator === "isNotEmpty") return !!sourceAnswer && sourceAnswer.length > 0;
if (operator === "equals") return sourceAnswer === value;
if (operator === "notEquals") return sourceAnswer !== value;
if (operator === "contains") {
if (Array.isArray(sourceAnswer)) return sourceAnswer.includes(value);
return typeof sourceAnswer === "string" && sourceAnswer.includes(value);
}
return true;
}
Field-Dependent Validation
Visibility alone is not enough. When field A's value is "B" and a dropdown appears, that dropdown should only accept values from a specific set — different from the set it would accept if A were "C". This is what conditionalValidation enables. The resolveValidation function reads the current answers, walks the rules, and returns the final merged validation:
example.ts
function resolveValidation(
field: FormField,
answers: Record<string, string | string[]>
): FieldValidation {
let resolved: FieldValidation = { ...field.validation };
for (const rule of field.conditionalValidation) {
const sourceAnswer = answers[rule.sourceFieldId];
let ruleMatches = false;
if (rule.operator === "equals") ruleMatches = sourceAnswer === rule.value;
if (rule.operator === "notEquals") ruleMatches = sourceAnswer !== rule.value;
if (rule.operator === "contains") {
ruleMatches = Array.isArray(sourceAnswer)
? sourceAnswer.includes(rule.value)
: typeof sourceAnswer === "string" && sourceAnswer.includes(rule.value);
}
if (ruleMatches) {
resolved = { ...resolved, ...rule.applyValidation };
}
}
return resolved;
}
Concrete Example: Bug Report Form
A form has three fields: a multiple-choice asking "What do you want to submit?" (Feedback / Bug report), a paragraph field that appears only for Feedback, and a dropdown severity selector that appears only for Bug report — and narrows further based on which team the respondent belongs to.
Inside FieldRenderer, for every visible field we call resolveValidation with the current answers and pass the result into React Hook Form's register. Because useWatch re-runs on every answer change, the validation always reflects the freshest state.
Trace what happens when a respondent selects "Bug report" in field 1:
React Hook Form fires its onChange handler and updates its internal store: { field_type: "Bug report" }.
useWatch returns a new snapshot. currentAnswers is now { field_type: "Bug report" }.
FieldRenderer re-renders because answers changed. For the paragraph field: isFieldVisible checks false → hides, unregisters. For the severity dropdown: checks true → renders.
resolveValidation walks conditionalValidation. No Infrastructure rule matches yet → all four options appear.
If the respondent later fills field_team = "Infrastructure", the rule matches and allowedValues narrows to ["High", "Critical"]. The DropdownField re-renders with only two options.
The whole chain runs synchronously inside the React render cycle. No effects, no timers, no server round-trips. The respondent sees the right options the instant the triggering field changes.
Warning
We also unregister hidden fields from React Hook Form so their required rules are not checked. If we do not do this, a respondent on a path that skips a required field will see a validation error for a question they never saw. The unregister call in the useEffect above is not optional — it is correctness.
7. Response Collection
The response collection pipeline is simpler than the builder, but it has its own set of concerns: validation against the published schema, filtering invisible fields, and presenting results.
Respondent View: React Hook Form
Each field registers itself with React Hook Form once and updates only that field's error state on validation failure — no global re-render for a single invalid field.
When the respondent submits, we filter out invisible fields before sending the payload. This prevents hidden fields from being included in the response data.
The form owner sees responses in a paginated table. Each row is a single response, and each column is a field. Fields with conditional visibility show empty cells for responses where the field was not shown. This is a straightforward render of the submitted answers keyed by field ID.
The response table is also where you add export features (CSV, Google Sheets sync) and basic analytics (average completion time, drop-off rate per field). Those are separate modules that read the same response data.
8. Performance Optimization
Performance is the difference between a form builder that feels snappy and one that feels like dragging through molasses. Here are the key optimizations.
React.memo with Granular Store Selectors
The biggest performance trap is re-rendering every FieldCard when the user types inside the settings panel of one field. We wrap FieldCard with React.memo and select only the specific field from the store:
example.ts
const FieldCard = React.memo(function FieldCard({ id }: { id: string }) {
// Only subscribes to this specific field
const field = useBuilderStore((state) => state.schema.fields.byIds[id]);
const isSelected = useBuilderStore((state) => state.selectedFieldId === id);
return (
<div className={isSelected ? "field-card selected" : "field-card"}>
{/* render based on field type */}
</div>
);
});
When the user edits field 3's label, only the component subscribing to byIds["field_3"] re-renders. Fields 1, 2, 4, 5 stay frozen.
Auto-Save with Debounce
We do not hit the save API on every keystroke. We wait until the user stops typing for 800ms before sending the patch:
The undo history is a simple array of past schema snapshots. We push a new snapshot when a destructive change happens (add, delete, reorder) but not on every individual keypress — we push after the 800ms debounce fires, so typing "What is your name?" produces one history entry, not 20. We limit past to 50 entries.
The builder imports DnD Kit, Zustand, and a rich settings panel with color pickers. None of this should land in the respondent bundle. Next.js code splitting at the route level handles this automatically, but we also split the settings panel using React.lazy:
The settings panel loads on the first click, not on page load. This shaves ~15KB off the initial builder bundle. For the respondent view, the equivalent optimization is that React Hook Form — which is only ~8KB gzipped — is the only form library that loads. Zustand and DnD Kit never reach the respondent's browser.
9. Testing Strategy
A form builder with conditional logic, drag and drop, and dynamic validation has a large state space. Here is how we test it.
Unit Tests: Pure Functions
isFieldVisible, resolveValidation, and buildRegisterOptions are pure functions. We test them exhaustively without React, without a browser, and without mounting a form.
The Zustand store actions are tested by creating a store instance, calling actions, and asserting the resulting state. We test add, remove, reorder, and cross-section moves.
example.ts
describe("BuilderStore", () => {
it("adds a field to the top level", () => {
const store = createBuilderStore();
store.addField("shortText");
expect(store.schema.fields.allIds.length).toBe(1);
expect(store.schema.fields.byIds[store.schema.fields.allIds[0]].type)
.toBe("shortText");
});
it("removes a section and all its children", () => {
const store = createBuilderStore();
store.addField("section");
const sectionId = store.schema.fields.allIds[0];
store.addField("shortText", sectionId);
store.removeField(sectionId);
expect(Object.keys(store.schema.fields.byIds).length).toBe(0);
});
});
Accessibility Audits
Every PR runs axe-core on the respondent view in all states: empty form, form with validation errors, and form with conditional logic branches. The drag handles, dropdowns, and error messages are tested for keyboard operability.
Tip
The most valuable tests for the renderer are snapshot tests of the FieldRenderer output given a specific answers object. For example: "given answers = { q1: 'Bug report' }, assert that field_text is not rendered and field_priority is rendered with all four options." These catch regressions when the visibility logic changes.
10. Accessibility
A form builder is a strange beast for accessibility: the builder is a visual drag-and-drop tool that is inherently difficult for keyboard-only users, but the rendered forms must be fully accessible. Here is how we handle both.
Keyboard Drag and Drop: Each FieldCard has a focusable drag handle. Use Space to pick up, Arrow keys to move, Enter to drop. No mouse required. DnD Kit provides KeyboardSensor out of the box.
ARIA for Field Cards: Each card uses role="listitem" with aria-label="Field: {''label{'}'}". The canvas uses role="list".
Error Announcements: Error messages use role="alert" and are connected to their inputs via aria-describedby. Screen readers announce errors immediately.
Conditional Logic Announcements: When a field appears or disappears due to a conditional rule, an aria-live="polite" region announces the change: "Priority field is now visible."
Respondent View: All form inputs have proper <label htmlFor={field.id}> associations. Required fields use aria-required="true". Invalid fields use aria-invalid="true".
Warning
The builder itself does not need to be fully keyboard accessible — it is a professional tool, and the typical user has a mouse. But the drag handles and settings panel must still work with a keyboard for users who rely on assistive technology. Test your builder with a screen reader at least once — you will be surprised at how much of the "intuitive" visual UI becomes completely unusable.
11. Key Takeaways
Six things to remember when building a no-code form builder:
Normalize your state from day one
byIds + allIds + childOrder turns a 50-field re-render into a 1-field re-render. Without this, the builder feels sluggish on any form larger than 10 fields.
Two surfaces, one schema
The builder mutates the schema; the renderer reads and validates it. The same FormSchema serves both. Different rendering strategies (CSR vs SSR) but the same data model.
Conditional logic needs a rule engine per field
Each field owns its conditionalRule and conditionalValidation. This makes deletion safe and keeps the schema self-documenting. No central rules table to maintain.
Field-dependent validation is separate from visibility
Visibility controls rendering. Validation controls allowed values. Both depend on current answers, but they serve different purposes. resolveValidation merges base validation with conditional overrides.
SSR for respondents, CSR for builders
Respondents arrive from a link — they need fast first paint. Builders are authenticated power users — they need rich interactivity. The optimal split is SSR for the renderer, CSR for the builder.
Unregister hidden fields to prevent phantom validation
A field that is not visible should not block form submission. useEffect + unregister is not optional — it is correctness. Skipping this means respondents see errors for questions they never saw.