Skip to content
Visual explainer 4h to learn 4 steps

Lists, keys & forms

Render lists correctly and build controlled forms with validation.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 15 of 36

In short

Lists are rendered by mapping arrays to JSX, and each item needs a stable key so React can track it. Controlled forms keep input values in state, which makes validation and submission straightforward.

Explained simply

Most apps show lists: products, messages, search results. In React you turn an array of data into an array of JSX with map. React then draws one item for each entry.

Each list item needs a key, a unique and stable label such as the item's database id. Keys let React tell items apart when the list changes. Without good keys, React can mix up which item is which, for example keeping text typed into one row attached to the wrong row.

Forms collect input from users. In a controlled form, React state holds every field value, and each change updates that state. This makes it easy to validate as the user types, disable the submit button, or show a live preview.

React 19 adds a second style: give the form an action function. React passes it the form data when the user submits, tracks whether it is still running, and resets the fields when it succeeds. Both styles are valid; pick what fits the form.

Press Play on a diagram to walk through it one step at a time.

FlowA controlled input
  1. 1
    User types

    The input fires a change event

  2. 2
    onChange handler

    Reads e.target.value

  3. 3
    Update state

    setEmail stores the new text

  4. 4
    Re-render

    value={email} shows the latest state

  5. 5
    Validate

    Compute errors from state and show them

CompareThree ways to build a form
Controlled
  • value + onChange per field
  • Live validation and previews
  • More code per field
  • Good for dynamic UIs
Uncontrolled + FormData
  • defaultValue, read on submit
  • Little code
  • Native validation works well
  • Good for simple forms
React 19 action
  • form action={fn}
  • isPending and result built in
  • Auto reset on success
  • Works with server actions

In depth

How keys guide React

When a list re-renders, React matches old and new items by key, not by position. Same key: keep that component and its state, update its props. New key: create a new component. Missing key: remove it.

With index keys, inserting an item at the top shifts every index by one. React thinks item 0 is still item 0, so the state of the first row, like an open editor or typed text, now belongs to a different product. Keys must be unique among siblings, stable across renders, and come from the data. Never generate them during render with Math.random() or crypto.randomUUID(): that creates new keys every time and remounts every row. Put the key on the outermost element returned from map; use a keyed Fragment when you return several elements.

CompareInserting "Kiwi" at the top of [Apple, Pear]
key={index}
  • Old: 0 Apple, 1 Pear
  • New: 0 Kiwi, 1 Apple, 2 Pear
  • React reuses row 0 for Kiwi
  • Apple's typed text now shows on Kiwi
key={item.id}
  • Old: a Apple, p Pear
  • New: k Kiwi, a Apple, p Pear
  • React adds one new row for k
  • Every row keeps its own state

Controlled and uncontrolled inputs

A controlled input has value={state} and an onChange that updates the state, so React is the source of truth. Use it when the UI reacts to each keystroke: live validation, character counters, formatting, or enabling a button.

An uncontrolled input keeps its own value in the DOM. You set a starting value with defaultValue and read the values on submit, usually with new FormData(form). It is less code for simple forms and works well with React 19 form actions.

Do not mix them on one input: value without onChange makes it read-only and React warns, and switching value from undefined to a string makes it flip from uncontrolled to controlled. Start text state as an empty string, not undefined. For checkboxes, use checked and defaultChecked instead of value.

Validation users can understand

Start with HTML: required, type="email", minLength, min, max and pattern give you free checks and the right mobile keyboard. Then add your own rules in JavaScript, and always validate again on the server, because client checks can be skipped.

Timing matters. Showing "invalid email" after the first keystroke is annoying. A common pattern is to validate a field when it loses focus (onBlur) and every field on submit. Make errors accessible: put the message in an element with an id, link it with aria-describedby on the input, and set aria-invalid="true". Move focus to the first invalid field on submit so keyboard and screen reader users know what to fix.

  • Native attributes first: required, type, minLength
  • Validate on blur and on submit, not every keystroke
  • aria-invalid plus aria-describedby for each error
  • The server must validate again

React 19 form actions

In React 19 you can pass a function to a form's action prop. On submit, React calls it with a FormData object; no preventDefault needed. useActionState wraps that function: it gives you the latest result (for example an errors object), a formAction to pass to the form, and an isPending flag. Your function receives the previous state and the form data and returns the next state.

Any component inside the form can call useFormStatus from react-dom to read pending, which is ideal for a reusable SubmitButton. When the action finishes successfully, React resets uncontrolled fields automatically. The same API works with Next.js server actions, so the form can submit to the server and still work before JavaScript loads.

SequenceSubmitting a form with useActionState
User
form
action function
React
  1. 1clicks Submit
    User to form: clicks Submit
  2. 2submit with FormData
    form to React: submit with FormData
  3. 3isPending becomes true
    React to React: isPending becomes true
  4. 4call with (prevState, formData)
    React to action function: call with (prevState, formData)
  5. 5return { errors } or { ok }
    action function to React: return { errors } or { ok }
  6. 6re-render with new state, pending false
    React to form: re-render with new state, pending false

Rendering long lists well

Filter and sort in render, before map: items.filter(...).toSorted(...).map(...). Do not call sort on state directly, since it mutates the array. If the calculation is expensive and runs on every keystroke, useMemo can cache it, but measure first.

A few hundred simple rows render fine. Thousands of rows, or rows with heavy content, make typing and scrolling slow because every row is a real DOM node. The fixes are pagination, a Load more button, or virtualization: libraries like TanStack Virtual or react-window render only the rows visible in the scroll area, so 10,000 items cost about the same as 30.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Render lists with map~1h
  2. 2
    Choose stable keys~1h
  3. 3
    Build controlled inputs~1h
  4. 4
    Validate a form and show errors~1h

Key points

  • Keys must be stable and unique among siblings; database IDs are ideal.
  • Avoid array indexes as keys when items can be reordered, added or removed.
  • A controlled input gets value from state and updates it in onChange.
  • Call e.preventDefault() in onSubmit to stop the full page reload.

Key terms

Tap a card to flip it. 0/4 known

Examples

tsx
function Signup() {
  const [email, setEmail] = useState('');
  const [items, setItems] = useState<{ id: string; email: string }[]>([]);
  const error = email && !email.includes('@') ? 'Enter a valid email' : '';
  function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (error || !email) return;
    setItems([...items, { id: crypto.randomUUID(), email }]); setEmail('');
  }
  return <form onSubmit={onSubmit}>
    <input value={email} onChange={(e) => setEmail(e.target.value)} />
    {error && <p role="alert">{error}</p>}
    <ul>{items.map((i) => <li key={i.id}>{i.email}</li>)}</ul>
  </form>;
}

Controlled input, derived validation and a keyed list.

A newsletter form with useActionState

Step 1: write subscribe(prevState, formData) that reads the email, validates it, and returns either an error or a success message. Step 2: useActionState gives the current state, the formAction and isPending. Step 3: pass formAction to the form's action prop. Step 4: show the error with role="alert" and disable the button while pending. No preventDefault and no controlled state are needed; the field resets after success.

tsx
import { useActionState } from "react";
type State = { error?: string; message?: string };

async function subscribe(_prev: State, formData: FormData): Promise<State> {
  const email = String(formData.get("email") ?? "");
  if (!email.includes("@")) return { error: "Enter a valid email" };
  await fetch("/api/subscribe", { method: "POST", body: formData });
  return { message: "Check your inbox!" };
}

export function Newsletter() {
  const [state, formAction, isPending] = useActionState(subscribe, {});
  return (<form action={formAction}>
    <input name="email" type="email" required aria-label="Email" />
    <button disabled={isPending}>{isPending ? "Sending..." : "Subscribe"}</button>
    <p role="alert">{state.error ?? state.message}</p>
  </form>);
}

Accessible error messages on blur

Step 1: keep the value and a touched flag in state. Step 2: derive the error from the value; do not store it. Step 3: show it only after the field was blurred, so users are not scolded while typing. Step 4: link the message with aria-describedby and set aria-invalid, so screen readers announce what is wrong.

tsx
import { useState } from "react";

export function PasswordField() {
  const [value, setValue] = useState("");
  const [touched, setTouched] = useState(false);
  const error = value.length < 12 ? "Use at least 12 characters" : "";
  const show = touched && error !== "";
  return (
    <label>
      Password
      <input type="password" value={value} onChange={(e) => setValue(e.target.value)} onBlur={() => setTouched(true)}
        aria-invalid={show} aria-describedby={show ? "pw-error" : undefined} />
      {show && <span id="pw-error">{error}</span>}
    </label>
  );
}

Quick reference

  • Keys: unique among siblings, stable, from the data (like id); never Math.random()
  • Index keys are fine only for static lists that never reorder, insert or delete
  • Controlled: value + onChange; uncontrolled: defaultValue + FormData on submit
  • Start text state as "" not undefined, to avoid uncontrolled-to-controlled warnings
  • React 19: const [state, formAction, isPending] = useActionState(fn, initial)
  • useFormStatus (from react-dom) gives pending to any child of a form
  • Link errors with aria-describedby and mark fields with aria-invalid
  • Thousands of rows? Paginate or virtualize with TanStack Virtual or react-window

Common mistakes

  • Using Math.random() as a key, which remounts items every render.
  • Setting value without onChange, which makes the input read-only.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why is key={Math.random()} a bad key?

Question 2

2An input has value={name} but no onChange. What happens?

Question 3

3In React 19, what does useActionState return?

Question 4

4Where can useFormStatus read the pending state from?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Render a list of countries from [{ code: "FR", name: "France" }, ...] as an unordered list with correct keys.

  2. Exercise 2medium

    Build a contact form with name and message (both required, message at least 20 characters) as an uncontrolled form. On submit, read FormData, show errors in a list, or log the values if valid.

  3. Exercise 3hard

    Write a reusable SubmitButton that shows "Saving..." and is disabled while its parent form's action runs, without receiving any props about pending state.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I use the array index as a key in React?
Only if the list is static and never reordered, filtered, or added to in the middle. Otherwise use a stable id from your data.
Do I need a form library like React Hook Form?
Not for small forms; React state or React 19 actions are enough. Libraries help with large forms that have many fields, complex validation or dynamic field arrays.
Is client-side validation enough?
No. It helps users, but anyone can bypass it, so always validate on the server too.

Go deeper

ShareXLinkedInWhatsApp