Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
Four versions of an add-task form, traced with real logs: a controlled input, a classic onSubmit, a form action that gets FormData and resets itself, and useActionState with a pending button from useFormStatus, plus the draft trick that keeps typed text after an error.
What you will learn
- Trace one keystroke through a controlled input
- Compare a classic onSubmit handler with a React 19 form action that receives FormData
- Write an action that returns the next state, errors included, and wire it with useActionState
- Show a pending button with useFormStatus, and know where it must live
Before you start
- React state with useState
- HTML forms: input names, select and submit buttons
A form has two jobs: get the text the user typed, and do something when they click the button. React 19 gives you two ways to handle the data. A controlled input keeps every keystroke in state. A form action lets the form hold its own fields and hands you all of them at once, as FormData, when the user submits.
This article traces four versions of an add-task form from the lecture's project, each with its real log output.
A controlled input: every key goes round once
import { useState } from 'react'
export default function TitleInput() {
// the text lives in state; the field only shows it
const [title, setTitle] = useState('')
console.log(`render, title = "${title}"`)
return (
<div className="card">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="New task"
/>
<p>{title.length} / 40 characters</p>
</div>
)
}
The text lives in state (line 5), and the field only shows it (line 11). Press B: the browser fires an input event, React calls onChange, e.target.value is "B", and setTitle("B") stores it. State changed, so React renders again, puts "B" back in the field and updates the counter.
render, title = ""
key: B
render, title = "B"
page: field = "B" | 1 / 40 characters
Give the input a value but no onChange and nothing writes the new text to state. Every render puts the empty string back, and the key disappears:
React warns: You provided a `value` prop to a form field without an `onChange` handler.
key: B
page: field = ""
The classic way: onSubmit
import { useState, type FormEvent } from 'react'
export default function ClassicForm() {
const [title, setTitle] = useState('')
const [tasks, setTasks] = useState<string[]>([])
function handleSubmit(e: FormEvent) {
e.preventDefault() // stop the page reload
setTasks([...tasks, title])
setTitle('') // we clear the field ourselves
}
return (
<form onSubmit={handleSubmit} className="card">
<input value={title}
onChange={(e) => setTitle(e.target.value)} />
<button type="submit">Add task</button>
<ul>
{tasks.map((t) => <li key={t}>{t}</li>)}
</ul>
</form>
)
}
typed: Buy milk, click: Add task
submit: page reload stopped = true
page: Buy milk | field = ""
By default a browser submit sends the form and reloads the page, so line 8 calls preventDefault(). Then we build the new list and clear the field ourselves. It works, but every step is ours to write.
A form action gets FormData
import { useState } from 'react'
export default function QuickAdd() {
const [tasks, setTasks] = useState<string[]>([])
// React calls add with the fields as FormData
function add(formData: FormData) {
const title = formData.get('title')
const priority = formData.get('priority')
setTasks([...tasks, `${title} (${priority})`])
}
return (
<form action={add} className="card">
<input name="title" placeholder="New task" />
<select name="priority">
<option>low</option><option>high</option>
</select>
<button type="submit">Add task</button>
<ul>
{tasks.map((t) => <li key={t}>{t}</li>)}
</ul>
</form>
)
}
The fields have no value and no onChange. The browser holds them, and each one has a name. Line 14 gives the form a function: action={add}. On submit, React stops the reload, builds FormData with one entry per named field, and calls add with it.
typed: Buy milk, picked: high, click: Add task
submit: page reload stopped = true | FormData: title=Buy milk, priority=high
page: Buy milk (high)
fields after: title = "" | priority = "low"
Look at the last line. After the action, React resets the form: every field goes back to its default, so the title is empty and priority is back to low. You didn't write any code to clear it.
| Job | onSubmit | Form action |
|---|---|---|
| Stop the reload | e.preventDefault() | React does it |
| Read the fields | value + onChange on each | A name on each, read from FormData |
| Clear the form | setTitle('') | React resets it |
The name matters: a field with no name is left out of FormData, so the action never sees it.
The action: state in, state out
export type State = {
tasks: string[]
error: string
draft: string // the typed text, kept on an error
}
const wait = (ms: number) =>
new Promise((r) => setTimeout(r, ms))
// previous state + FormData in, new state out
export async function addTask(
prev: State,
formData: FormData,
): Promise<State> {
const title = String(formData.get('title')).trim()
if (title.length < 3) {
const error = 'Please type at least 3 letters.'
return { ...prev, error, draft: title }
}
await wait(1500) // pretend to save on a server
const tasks = [...prev.tasks, title]
return { tasks, error: '', draft: '' }
}
addTask takes the previous state and the FormData and returns a promise of the next state. A title shorter than three letters isn't an exception: it returns the previous state with an error message and the typed text as draft. A typo is state, not a crash. Otherwise it waits 1.5 seconds to pretend it is saving on a server and returns the new list.
useActionState wires it up
import { useActionState } from 'react'
import { addTask } from './04-addTask'
import SaveButton from './06-SaveButton'
const start = { tasks: [], error: '', draft: '' }
export default function AddTaskForm() {
const [state, formAction, isPending] =
useActionState(addTask, start)
console.log('render, isPending =', isPending)
return (
<form action={formAction} className="card">
<input name="title"
defaultValue={state.draft} />
<SaveButton />
{state.error && (
<p className="error">{state.error}</p>
)}
<ul>
{state.tasks.map((t) => <li key={t}>{t}</li>)}
</ul>
</form>
)
}
useActionState takes the action and a start state, and gives back three things: the current state, a formAction that calls addTask with the previous state for you, and isPending. React keeps the state between renders, and whatever the action returns replaces it.
One submit on a timeline
render, isPending = false
typed: Buy milk, click: Add task
render, isPending = true
page: button = Adding... (disabled: true)
render, isPending = false
page: Buy milk | field = ""
An error is just state
Type "Hi" and click. The action returns the error and the draft, and lines 17 to 19 draw the error under the field:
render, isPending = false
typed: Hi, click: Add task
render, isPending = true
render, isPending = false
page: error = Please type at least 3 letters.
page: field = "Hi" | tasks: none
without defaultValue: field = ""
React resets the form after every action, after an error too. Without defaultValue, the field would go empty and the user would lose what they typed (the last line). With defaultValue={state.draft}, the reset puts "Hi" back.
useFormStatus asks the form above it
import { useFormStatus } from 'react-dom'
// must sit INSIDE a <form>: it reads its status
export default function SaveButton() {
const { pending } = useFormStatus()
return (
<button type="submit" disabled={pending}>
{pending ? 'Adding...' : 'Add task'}
</button>
)
}
useFormStatus looks up the tree for the nearest <form> and reads its status. SaveButton is rendered inside the form, so while the action runs pending is true and the button is disabled, so nobody can click it twice.
Now the mistake. Call it in the component that renders the form:
export default function BrokenForm() {
// the mistake: asked where the form is RENDERED
const { pending } = useFormStatus()
const [, action] = useActionState(addTask, start)
return (
<form action={action} className="card">
<input name="title" placeholder="New task" />
<button type="submit" disabled={pending}>
{pending ? 'Adding...' : 'Add task'}
</button>
</form>
)
}
BrokenForm while saving: button = Add task (disabled: false)
AddTaskForm while saving: button = Adding... (disabled: true)
There is no form above BrokenForm, the form is below it, so pending is always false and the button stays clickable while saving. Two fixes: move the button into its own child component, like SaveButton, or use isPending from useActionState, which belongs to this component anyway.
Recap
| Tool | What it does |
|---|---|
| Controlled input | value from state, onChange writes state; every key goes round once |
onSubmit | You stop the reload, update state and clear the fields |
<form action={fn}> | React calls fn(formData) with every named field, then resets the form |
useActionState | Action and start state in; state, form action and isPending out |
defaultValue={state.draft} | Keeps typed text after an error reset |
useFormStatus | Reads the status of the form it sits inside |
Try it yourself: add a priority select to AddTaskForm and return it in the state, so a failed submit keeps both the text and the picked priority. Next: context and custom hooks.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
React State, Events, Lists and Conditional Rendering: Follow One Click
Follow one click through a React counter, render by render: what useState hands back, why a plain variable never updates the page, ternaries and &&, map with keys, and the index-as-key bug that moves a typed note to the wrong task.
React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
Watch useEffect on a timeline with real render counts: the dependency array deciding re-runs, a timer cleanup that keeps one timer alive, the leak StrictMode exposes, and two effects you should delete (a copied total and a click flag).
Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
A task board where the filter is stuck in one component, fixed by lifting it to App. Then useRef as a box React does not watch (three clicks, zero renders), a ref that refocuses an input, and the tree React DevTools shows.
React Context and Custom Hooks: Share One Value, Reuse the Logic
Replace three hops of prop drilling with a context, see the nearest Provider win, count which components re-render on a theme toggle, then pull localStorage logic into a useLocalStorage hook and break the rules of hooks on purpose.
