Sub topic 11
Forms that work before JavaScript loads
This chapter covers how a React 19 form can submit correctly before the JavaScript bundle has loaded and hydrated. It assumes you have read the earlier chapters on <form action>, useActionState, useFormStatus, and Server Functions. It also assumes you know the difference between server rendering and hydration, and that you can read a basic HTML form with name attributes.
Why this matters
A server-rendered page reaches the browser as HTML before the JavaScript arrives. On a slow phone or a flaky network, the gap between "the form is visible" and "React has attached its handlers" can last seconds. Some users also never get the script, because it was blocked, it failed to download, or an extension broke it.
If a user submits during that gap, one of two things happens:
- The form depends on client-side JavaScript. The click does nothing, or the browser does a plain GET that reloads the page and drops the typed values.
- The form is built so the browser can submit it without React. The submission reaches the server, which does the work and returns a page.
The second behavior is called progressive enhancement. The HTML form works first, and JavaScript improves it afterward with pending states, optimistic UI, and no full page reload.
What the browser does with a form
A browser can submit a form with no JavaScript. It reads the <form> element's action URL and method. It collects every field that has a name attribute, encodes the values, and sends a request. Fields without a name are ignored.
<form action="/subscribe" method="post">
<input name="email" type="email" required />
<button type="submit">Subscribe</button>
</form>React's <form action={fn}> takes a function instead of a URL. A function cannot be written into HTML. That is why the Server Function case differs from the client function case.
Which actions can work before hydration
The action prop accepts a function in both cases, but only one can be submitted before hydration.
| Kind of action | Runs before hydration? | Reason |
|---|---|---|
| Client function (defined in a component or imported into client code) | No | The function exists only in the JavaScript bundle that has not run yet. |
| Server Function (marked with `"use server"`), in a supporting framework | Yes | The server renders a reference to the function into the HTML. The browser submits to the server, which finds the function by that reference and calls it. |
Using a Server Function this way requires a framework or bundler that implements React's server features. Plain client-side React with no server does not. React supplies the primitives, and your framework wires up the HTML, the request handling, and the routing. The details differ between frameworks, so check how yours handles form submissions.
The sequence is below.
A form that survives early submission
Here is a newsletter form. The Server Function validates the email and returns a state object. The component passes it to useActionState, as in earlier chapters.
// actions.js
"use server";
const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
export async function subscribe(previousState, formData) {
const email = String(formData.get("email") ?? "").trim();
if (!EMAIL_PATTERN.test(email)) {
return { error: "Enter a valid email address.", email, subscribed: false };
}
// Save the address to your data store here.
return { error: null, email: "", subscribed: true };
}
// SubscribeForm.jsx
"use client";
import { useActionState } from "react";
import { subscribe } from "./actions";
const initialState = { error: null, email: "", subscribed: false };
export function SubscribeForm() {
const [state, formAction, isPending] = useActionState(
subscribe,
initialState,
"/newsletter"
);
return (
<form action={formAction}>
<input name="email" type="email" defaultValue={state.email} />
<button type="submit" disabled={isPending}>
Subscribe
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.subscribed && <p>Thanks, you are on the list.</p>}
</form>
);
}Three details make this work before hydration.
- The action is a Server Function.
subscribelives in a"use server"file, so the server can run it from a plain browser request. useActionStatereceives a third argument."/newsletter"is the permalink, which is the URL of the page that holds this form and shows its result. React writes it into the form so a pre-hydration submit goes to that page.- Inputs are uncontrolled. The field has a
nameand usesdefaultValue. A controlled input driven byuseStatehas no state until hydration, so it cannot carry the value back after a full-page submit.
What the permalink does
Without a permalink, the page does not know where to send an early submission. The server needs a page to render the returned state into. On a no-JavaScript submit, the sequence runs like this:
- The browser posts the fields to the server.
- The server runs
subscribe, using the form's initial state aspreviousState. - The server renders the page at the permalink with the returned state, so
state.errororstate.subscribedshows in the HTML. - The browser displays that page.
The permalink must point to a page that renders the same form with the same Server Function. If the page uses a different action or has a different shape, the state returned on a no-JavaScript submit will not match the form. The permalink also matters when the form appears on a dynamic route. Use the URL that renders it, including any params.
What changes after hydration
Once the script loads, React takes over the same form without changing your code. Submits no longer reload the page. React calls the Server Function and updates only the parts that changed. isPending, useFormStatus, and useOptimistic begin working. The transition from HTML-only behavior to client-enhanced behavior is the enhancement in "progressive enhancement".
What is unavailable before hydration
Every hook-driven behavior from earlier chapters depends on JavaScript. Plan for the HTML-only path to be plainer.
| Feature | Before hydration |
|---|---|
| `isPending` and `useFormStatus` | Never true. The browser shows its own loading indicator while the request runs. |
| `useOptimistic` | No temporary value. The user sees the result only on the next page. |
| Validation in `onChange` handlers | Does not run. Only server validation and built-in HTML attributes work. |
| Controlled inputs | No React state exists to hold the value. |
| Automatic form reset | Not applicable. The page reloads, so field values come from `defaultValue`. |
Because the page reloads, any value you want to keep after an error must be returned in your state. In the example, a failed submit returns email, and defaultValue={state.email} puts it back in the field. After a successful submit it returns an empty string, so the field clears.
Passing extra arguments safely
A form often needs a context value, such as which item to update. Do not rely on a closure created inside a client component for this. Use bind to attach the value to the Server Function, which keeps the reference serializable.
// actions.js
"use server";
export async function renameProject(projectId, previousState, formData) {
const name = String(formData.get("name") ?? "").trim();
if (name.length === 0 || name.length > 100) {
return { error: "Name must be 1 to 100 characters.", name };
}
// Check that the current user may edit projectId, then save here.
return { error: null, name };
}
// RenameForm.jsx
"use client";
import { useActionState } from "react";
import { renameProject } from "./actions";
export function RenameForm({ projectId, currentName }) {
const boundAction = renameProject.bind(null, projectId);
const [state, formAction, isPending] = useActionState(
boundAction,
{ error: null, name: currentName },
`/projects/${projectId}`
);
return (
<form action={formAction}>
<input name="name" defaultValue={state.name} />
<button type="submit" disabled={isPending}>
Rename
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Bound arguments are visible to the client and can be changed by a determined user, so the server must still check that the user may edit projectId. A hidden <input type="hidden" name="projectId"> has the same property. Neither is a trust boundary.
Testing the no-JavaScript path
Do not assume the path works. Check it directly.
- Open your browser's developer tools and disable JavaScript. In Chrome, use the Command Menu and run "Disable JavaScript".
- Reload the page and submit the form with valid data. The page should reload and show the success state.
- Submit invalid data. The page should reload with the error message and the typed value still in the field.
- Throttle the network to a slow profile and submit while the bundle is still loading. This tests the real-world gap, not only the fully disabled case.
Also test the successful path with JavaScript enabled, to confirm the enhanced version behaves the same.
Common mistakes
- Missing
nameattributes. The browser drops unnamed fields, andformData.getreturnsnull. - Using a client function as the action and expecting it to run early. It cannot. Move the logic to a Server Function, or accept that the form needs JavaScript.
- Omitting the permalink. The form may still work after hydration, so the bug shows up only for early or no-JavaScript submits.
- A permalink that points to a different page. The user lands somewhere that does not show the result of the submission.
- Relying on client-only validation. It does not run before hydration, and the server cannot trust it anyway.
- Storing the result only in client state. After a full-page submit, that state is gone. Return everything the page needs from the action.
When to bother
Forms that matter most before hydration are sign-in, checkout, search, and contact forms, where a failed early click costs the user real time. A dashboard filter that exists only for logged-in users on fast connections matters less. The cost is small if you start with it. It means using named uncontrolled inputs, Server Functions as actions, a permalink, and server-side validation. You are likely to want all of these anyway.
Exercise
A form in your app uses <form action={saveDraft}>, where saveDraft is an async function defined inside the client component. Users on slow connections report that submitting right after the page appears does nothing. Why does this happen, and what two changes are needed to fix it?
Show answer
saveDraft exists only in the JavaScript bundle, which has not loaded or hydrated yet, so the server has no way to run it when the browser submits. To fix it, first move the logic into a Server Function in a "use server" file so the form can submit to the server. Second, make sure the fields have name attributes and, if you use useActionState, pass the page's URL as the third (permalink) argument so the result can be rendered after a full-page submit. The server also needs to validate the input, since this is now an ordinary request.
Exercise
After a failed no-JavaScript submit, the name field comes back empty even though the user typed a value. The input is <input name="name" value={name} onChange={...} /> with name from useState. Give the cause and a fix.
Show answer
The input is controlled by client state, and that state does not exist until hydration, so after a full-page reload it starts at its initial value. Make the input uncontrolled with defaultValue, and have the Server Function return the submitted value in its state, for example { error, name }. Render defaultValue={state.name} so the server-rendered page contains the value the user typed.