Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Hooks

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Hooks

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.

JobonSubmitForm action
Stop the reloade.preventDefault()React does it
Read the fieldsvalue + onChange on eachA name on each, read from FormData
Clear the formsetTitle('')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

isPending from submit to return Render 1 isPending false Render 2: isPending true button "Adding...", disabled Render 3 Buy milk, form reset click action waits 1.5 s action returns
isPending is true from the submit until the action returns. Then React draws the returned state.
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

ToolWhat it does
Controlled inputvalue from state, onChange writes state; every key goes round once
onSubmitYou stop the reload, update state and clear the fields
<form action={fn}>React calls fn(formData) with every named field, then resets the form
useActionStateAction and start state in; state, form action and isPending out
defaultValue={state.draft}Keeps typed text after an error reset
useFormStatusReads 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.

Keep going in React · 51 of 59

Previous
Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
Next post
React Context and Custom Hooks: Share One Value, Reuse the Logic
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A controlled input: every key goes round once
  • The classic way: onSubmit
  • A form action gets FormData
  • The action: state in, state out
  • useActionState wires it up
  • One submit on a timeline
  • An error is just state
  • useFormStatus asks the form above it
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.