react
react copied to clipboard
Add `React.useActionState`
Overview
Depends on https://github.com/facebook/react/pull/28514
This PR adds a new React hook called useActionState
to replace and improve the ReactDOM useFormState
hook.
Motivation
This hook intends to fix some of the confusion and limitations of the useFormState
hook.
The useFormState
hook is only exported from the ReactDOM
package and implies that it is used only for the state of <form>
actions, similar to useFormStatus
(which is only for <form>
element status). This leads to understandable confusion about why useFormState
does not provide a pending
state value like useFormStatus
does.
The key insight is that the useFormState
hook does not actually return the state of any particular form at all. Instead, it returns the state of the action passed to the hook, wrapping it and returning a trackable action to add to a form, and returning the last returned value of the action given. In fact, useFormState
doesn't need to be used in a <form>
at all.
Thus, adding a pending
value to useFormState
as-is would thus be confusing because it would only return the pending state of the action given, not the <form>
the action is passed to. Even if we wanted to tie them together, the returned action
can be passed to multiple forms, creating confusing and conflicting pending states during multiple form submissions.
Additionally, since the action is not related to any particular <form>
, the hook can be used in any renderer - not only react-dom
. For example, React Native could use the hook to wrap an action, pass it to a component that will unwrap it, and return the form result state and pending state. It's renderer agnostic.
To fix these issues, this PR:
- Renames
useFormState
touseActionState
- Adds a
pending
state to the returned tuple - Moves the hook to the
'react'
package
Reference
The useFormState
hook allows you to track the pending state and return value of a function (called an "action"). The function passed can be a plain JavaScript client function, or a bound server action to a reference on the server. It accepts an optional initialState
value used for the initial render, and an optional permalink
argument for renderer specific pre-hydration handling (such as a URL to support progressive hydration in react-dom
).
Type:
function useActionState<State>(
action: (state: Awaited<State>) => State | Promise<State>,
initialState: Awaited<State>,
permalink?: string,
): [state: Awaited<State>, dispatch: () => void, boolean];
The hook returns a tuple with:
-
state
: the last state the action returned -
dispatch
: the method to call to dispatch the wrapped action -
pending
: the pending state of the action and any state updates contained
Notably, state updates inside of the action dispatched are wrapped in a transition to keep the page responsive while the action is completing and the UI is updated based on the result.
Usage
The useActionState
hook can be used similar to useFormState
:
import { useActionState } from "react"; // not react-dom
function Form({ formAction }) {
const [state, action, isPending] = useActionState(formAction);
return (
<form action={action}>
<input type="email" name="email" disabled={isPending} />
<button type="submit" disabled={isPending}>
Submit
</button>
{state.errorMessage && <p>{state.errorMessage}</p>}
</form>
);
}
But it doesn't need to be used with a <form/>
(neither did useFormState
, hence the confusion):
import { useActionState, useRef } from "react";
function Form({ someAction }) {
const ref = useRef(null);
const [state, action, isPending] = useActionState(someAction);
async function handleSubmit() {
// See caveats below
await action({ email: ref.current.value });
}
return (
<div>
<input ref={ref} type="email" name="email" disabled={isPending} />
<button onClick={handleSubmit} disabled={isPending}>
Submit
</button>
{state.errorMessage && <p>{state.errorMessage}</p>}
</div>
);
}
Benefits
One of the benefits of using this hook is the automatic tracking of the return value and pending states of the wrapped function. For example, the above example could be accomplished via:
import { useActionState, useRef } from "react";
function Form({ someAction }) {
const ref = useRef(null);
const [state, setState] = useState(null);
const [isPending, setIsPending] = useTransition();
function handleSubmit() {
startTransition(async () => {
const response = await someAction({ email: ref.current.value });
setState(response);
});
}
return (
<div>
<input ref={ref} type="email" name="email" disabled={isPending} />
<button onClick={handleSubmit} disabled={isPending}>
Submit
</button>
{state.errorMessage && <p>{state.errorMessage}</p>}
</div>
);
}
However, this hook adds more benefits when used with render specific elements like react-dom <form>
elements and Server Action. With <form>
elements, React will automatically support replay actions on the form if it is submitted before hydration has completed, providing a form of partial progressive enhancement: enhancement for when javascript is enabled but not ready.
Additionally, with the permalink
argument and Server Actions, frameworks can provide full progressive enhancement support, submitting the form to the URL provided along with the FormData from the form. On submission, the Server Action will be called during the MPA navigation, similar to any raw HTML app, server rendered, and the result returned to the client without any JavaScript on the client.
Caveats
There are a few Caveats to this new hook:
Additional state update: Since we cannot know whether you use the pending state value returned by the hook, the hook will always set the isPending
state at the beginning of the first chained action, resulting in an additional state update similar to useTransition
. In the future a type-aware compiler could optimize this for when the pending state is not accessed.
Pending state is for the action, not the handler: The difference is subtle but important, the pending state begins when the return action is dispatched and will revert back after all actions and transitions have settled. The mechanism for this under the hook is the same as useOptimisitic.
Concretely, what this means is that the pending state of useActionState
will not represent any actions or sync work performed before dispatching the action returned by useActionState
. Hopefully this is obvious based on the name and shape of the API, but there may be some temporary confusion.
As an example, let's take the above example and await another action inside of it:
import { useActionState, useRef } from "react";
function Form({ someAction, someOtherAction }) {
const ref = useRef(null);
const [state, action, isPending] = useActionState(someAction);
async function handleSubmit() {
await someOtherAction();
// The pending state does not start until this call.
await action({ email: ref.current.value });
}
return (
<div>
<input ref={ref} type="email" name="email" disabled={isPending} />
<button onClick={handleSubmit} disabled={isPending}>
Submit
</button>
{state.errorMessage && <p>{state.errorMessage}</p>}
</div>
);
}
Since the pending state is related to the action, and not the handler or form it's attached to, the pending state only changes when the action is dispatched. To solve, there are two options.
First (recommended): place the other function call inside of the action passed to useActionState
:
import { useActionState, useRef } from "react";
function Form({ someAction, someOtherAction }) {
const ref = useRef(null);
const [state, action, isPending] = useActionState(async (data) => {
// Pending state is true already.
await someOtherAction();
return someAction(data);
});
async function handleSubmit() {
// The pending state starts at this call.
await action({ email: ref.current.value });
}
return (
<div>
<input ref={ref} type="email" name="email" disabled={isPending} />
<button onClick={handleSubmit} disabled={isPending}>
Submit
</button>
{state.errorMessage && <p>{state.errorMessage}</p>}
</div>
);
}
For greater control, you can also wrap both in a transition and use the isPending
state of the transition:
import { useActionState, useTransition, useRef } from "react";
function Form({ someAction, someOtherAction }) {
const ref = useRef(null);
// isPending is used from the transition wrapping both action calls.
const [isPending, startTransition] = useTransition();
// isPending not used from the individual action.
const [state, action] = useActionState(someAction);
async function handleSubmit() {
startTransition(async () => {
// The transition pending state has begun.
await someOtherAction();
await action({ email: ref.current.value });
});
}
return (
<div>
<input ref={ref} type="email" name="email" disabled={isPending} />
<button onClick={handleSubmit} disabled={isPending}>
Submit
</button>
{state.errorMessage && <p>{state.errorMessage}</p>}
</div>
);
}
A similar technique using useOptimistic
is preferred over using useTransition
directly, and is left as an exercise to the reader.
Thanks
Thanks to @ryanflorence @mjackson @wesbos (https://github.com/facebook/react/issues/27980#issuecomment-1960685940) and Allan Lasser for their feedback and suggestions on useFormStatus
hook.
Comparing: 17eaacaac167addf0c4358b4983f054073a0626d...643e562135220b52b8ca97161ab7c71943feda06
Critical size changes
Includes critical production bundles, as well as any change greater than 2%:
Significant size changes
Includes any change greater than 0.2%:
Expand to show
Generated by :no_entry_sign: dangerJS against 643e562135220b52b8ca97161ab7c71943feda06
In your PR description, what is the if (errorMessage != null) {
for?
I guess there is a typo in the following code snippet:
Good call @sophiebits, I was thinking it it's null you would do something with it like handle a re-direct, but in the other examples the action would handle that for you so it makes sense to drop it here.
Nice catch @meghsohor, fixed and I re-formatted all the examples to fix the syntax errors and formatting.
Reading between the lines a bit here, could this be used allow you to opt out of Next.js' serial server action processing?
@tom-sherman I'm not familiar with the Next processing for server actions, but I don't think anything about this would change their implementation and that wasn't a motivating factor. It's the same hook, with a different name, a pending value, and just moved to the 'react'
package.
In case anyone is reading the PR description examples and wondering (like I did) what types the first returned array element can be (errorMessage
in the example, which looks like string | null
type):
It looks like the first argument is just state
, and it can be any type:
https://github.com/facebook/react/blob/651adbaad55a596b3c7f1d7ff3ccb3c454728076/packages/react-debug-tools/src/ReactDebugHooks.js#L656-L659
Also confirmed over here:
Correct, it's whatever data your action returns, just like useFormState. Since successful actions will typically navigate on success, it's probably most common to use the return value to show an error, which is the only reason I used an errorMessage in the example.
Source: https://twitter.com/rickhanlonii/status/1765592038026641571
Thanks @karlhorky, I added the type to the reference section, updated the code examples to use state
instead.
Great PR and great to see how fast the team responds to the feedback! Leaving just my 2 cents here from an educational perspective:
I ran into the same confusion when I wrote my blog post about Forms in Next. Now if I understand this PR correctly, useFormState
will go away in favor or useActionState
, but useFormStatus
will stay around as a more fine-grained primitive (where I didn't have any usage yet, but probably more interesting for library/framework authors).
Now I have a kinda related question. In my article, I wanted to show how to trigger a reactive toast message once an action returns its response. But I had no indicator for the new formState
, therefore I had to return a timestamp
(read: timestamp: Date.now()
) from the action as formState
, so that I could reactively show a toast message in a custom hook:
import { useRef, useEffect } from 'react';
import { toast } from 'react-hot-toast';
type FormState = {
message: string;
fieldErrors: Record<string, string[] | undefined>;
timestamp: number;
};
const useToastMessage = (formState: FormState) => {
const prevTimestamp = useRef(formState.timestamp);
const showToast =
formState.message &&
formState.timestamp !== prevTimestamp.current;
useEffect(() => {
if (showToast) {
if (formState.status === 'ERROR') {
toast.error(formState.message);
} else {
toast.success(formState.message);
}
prevTimestamp.current = formState.timestamp;
}
}, [formState, showToast]);
};
export { useToastMessage };
Since the returned message
could be the same (e.g. "Successful request.") for two successive requests, I had to introduce the timestamp
which does the check to see whether its a new instance of message
to show as toast. Otherwise the toast would have only shown once:
formState.timestamp !== prevTimestamp.current
Now I see there would be a way around this with useActionState
, e.g. checking if the pending
state goes from true
to false
and showing the toast message
(if there is any in the formState
). Am I correct or is the best practice any other way? Thanks for you input! I want to showcase these use case in the best possible way :)
Hey there,
I hope you don't mind me jumping into the conversation.
I've been catching up the discussion that led to these changes and I'm genuinely excited to see these APIs receiving more attention.
I've got a few thoughts on how React could take this even further and help developers to create forms that are progressively enhanced rather than (un)gracefully degraded.
Motivation and suggestions
One of the key advantages, for me, of useFormState()
/useActionState()
and <form action={action}>
is their ability to create isomorphic/universal forms that are progressively enhanced.
However, the current API lacks some nuance needed for isomorphic forms:
1. Access to Payload
for enhanced abstractions
One challenge is the difficulty in creating abstractions that gracefully degrade due to limited access to Payload
. In PHP, for example, you have the convenient $_POST
object for accessing form data anywhere.
I'd like Payload
to be as easily accessible as $_POST
so that all my uncontrolled form inputs could look something like this:
<input type="text" name="title" defaultValue={payload?.get('title')} />
If I was to make a custom <Input>
-component that supported this now, I couldn't rely on React giving me access to the payload, without forcing a specific envelope on the server.
Suggestion
I propose updating the hook to return a tuple (or object) with:
-
dispatch
: the method to call to dispatch the wrapped action -
state
: the last state the action returned -
payload
(🆕): the last payload sent to the server (null | Payload
) -
pending
: the pending state of the action and any state updates contained
function useActionState<State, Payload>(
action: (state: Awaited<State>, payload: Payload) => State,
initialState: Awaited<State>,
permalink?: string,
): [
state: State,
dispatch: (payload: Payload) => Promise<State>,
payload: null | Payload,
pending: boolean;
];
- When JS is loaded, we should have access to the
Payload
through the latest dispatch - When JS isn't loaded, we should have access to the
Payload
through the incomingRequest
Another benefit is that having every API handler to returning the Payload
adds unnecessary payload on every "SPA-request".
2. Consistent behavior with/without JS as a default
Currently, the behavior differs between JS and no-JS scenarios. When a form is submitted without JS, all inputs clear, whereas with JS enabled, they do not.
It seems unlikely that a user would fill out a full form before JS is loaded, but this behavior makes it needlessly difficult to implement forms that work well without JS.
Suggestion
Similar: #27876
I suggest aligning React's behavior with JS to mimic the web's default behavior without JS. This means putting the form inputs back to their defaultValue
when submitted.
While this adjustment may seem inconvenient and annoying, it will provide clarity on implementing forms that work well regardless of JS availability, which to me aligns with one of the main goals of React's APIs in this context.
@KATT
Regarding the second point:
I suggest aligning React's behavior with JS to mimic the web's default behavior without JS. This means putting the form inputs back to their defaultValue when submitted.
This is indeed what we're planning to do in React 19, but with a few caveats:
- We only reset if a function is passed to
action
. - Only uncontrolled form inputs will be reset.
- The form is reset to
defaultValue
only once the action is completed. That way you can updatedefaultValue
to a new value from the server right before the reset happens. (This is different from how regularform.reset()
works because it's asynchronous.) - To allow you to implement the same behavior manually, we'll provide a
resetForm
import fromreact-dom
that works the same way: reset the form the todefaultValue
once the current action/transition has completed.
Regarding the first point, I'm not sure your Payload proposal makes sense to me. What is the value of Payload after the submission has completed? It sounds like maybe you intend for it to be null
, but in that case, the defaultValue
in your example would also be empty, which conflicts with the idea of resetting back to defaultValue
upon submission.
This is indeed what we're planning to do in React 19, but with a few caveats:
🥳 . All makes sense.
Appreciate your responses here. I'll elaborate more on the Payload
👇
Regarding the first point, I'm not sure your Payload proposal makes sense to me. What is the value of Payload after the submission has completed? It sounds like maybe you intend for it to be
null
, but in that case, thedefaultValue
in your example would also be empty, which conflicts with the idea of resetting back todefaultValue
upon submission.
Server-side validation errors. Server actions can be completed without the form being "done".
Right now, any error response would have to return the full payload as well in order not to render with empty inputs.
I don't see many people doing forms that work nicely without JS without easy access to payload, it adds a quite a bit of grokking to know that you should return "last payload" on your server in order to render the invalid form with the last submission's values.
It doesn't conflict the resetting proposal if the order of operations is right in the "JS-enabled" perspective:
- Form is submitted / action is dispatched
-
useActionState()
now is a new tuple/object inpending
with the newpayload
- My
<input />
is re-rendered with a newdefaultValue
(nothing happens since updating thedefaultValue
doesn't actually update it) - Action completes, resets the form to their
defaultValue
s (which is the latest payload since I useddefaultValue={payload?.get('title')}
Might be some nuance there that needs tweaking to align it to how a browser without JS would work, especially in cases of frenzy-clicking submit buttons, but you get my point
Concrete example where this causes a problem
@acdlite, how would you suggest handling a form that returns validation errors on the server which would work nicely with and without JS and render inputs with the last submitted values? Is it straight-forward enough to get most people using React to do it "the right way"?
I'll try to describe it here in more detail:
// /app/posts/_actions.ts
'use server';
// [...] imports
const postSchema = z.object({
title: z.string().trim().min(10),
content: z.string().trim().min(50),
});
export async function createPost(_: unknown, formData: FormData) {
const result = postSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
return {
error: result.error.flatten(),
// in order to render with the last values, we gotta return formData here :(
formData,
};
}
// i don't care about the result of successes since i just redirect
const post = await prisma.post.create(result.data);
redirect(`/post/${post.id}`);
}
Returning payload as part of State
here isn't great:
- adds extra complexity to the server actions to handle standard functionality
- when JS is enabled it's completely unnecessary payload since it can be grabbed when dispatching
- without returning the payload as part of
State
, you can't re-render the form's inputs with the rightdefaultValue
/value
- what if I had a file input with a big file? is that gonna be passed back-and-forth when it doesn't even need to be passed at all?
I just used an input validation error as an example here, but it could be a unique validation error from the database or something else that couldn't be handled gracefully in the browser before it hit the server
@KATT Your proposal/argument was compelling. We've spent some time evaluating a variant of your proposal (useFormStatus would have previous payload), but are currently leaning towards not adding it. Mainly due to hydration.
When you use the sent FormData directly to represent the "current" state of a form, there's no way to reset the form or control a field. E.g. filtering out invalid characters or upper case the field from the action. If that was ok, we could do something even better and just automatically set the value of a form field to the last set. Since it's not ok, that's why it's not a sufficient solution, you may need to move the source of truth into the state later on once you need to be able to control it from the action. That doesn't dismiss that you could start with the last-sent payload and then later upgrade to putting it inside useActionState as need arrises.
However, the main problem with surfacing the last sent payload is that we would still need to serialize it into the HTML for hydration. Since the current model is that even after submitting an MPA form, we can still hydrate the second attempt. It doesn't stay in no-JS land afterwards. So it wouldn't be better than the useActionState
option and you still might need the useActionState
option later when the need arrises. In that case we'd have to keep serializing the whole form - including files potentially - for hydration purposes in case you end up using it.
Therefore, it seems like it's better to stay with the model where previous state is returned from useActionState
. That way you can control it and filter out anything that's not needed (such as Blobs).
There are a couple of things we can do to improve that experience though:
- I've already added support for returning FormData from an Action. So that for a simple form you can just return the payload.
- We have plans for an optimization that would exclude serializing the "previous state" argument if it's completely unused.
- It would still serialize it in the return path though. For MPA form submissions this is still needed in the HTML for hydration purposes for the reasons mentioned above. However, for client submissions we can avoid sending this down if we already have a copy on the client using the Temporary References mechanism.
This mode is still opt-in though in that by default the form would not preserve user state unless you passed it through useActionState
and did something like <input name="field" defaultValue={formData.has('field') ? formData.get('field') : lastSaved.field} />
.
We've also evaluated a few other modes. Including we could automatically restore the last submitted field to inputs so that it's instead preserved by default and you have to call reset()
explicitly inside a Server Action to clear it. However, once you get into that - afterwards you still back to square one. It's a bit leaky in terms of abstractions and it's also not necessarily always a better default.
I will also say that it's not expected that uncontrolled form fields is the way to do forms in React. Even the no-JS mode is not that great. We consider it more of an easy way to start, or good enough. But a good form should include controlled inputs, live-synchronized to localStorage or remotely (e.g. using useOptimistic
) and deal with things like race conditions between submitting and returning the response (our resetting can blow away changes in this gap unless you disable form for example).
Therefore the expectation of these APIs is more that they're kind of "close to the metal" with some composition enhancements and you can get basic stuff done with uncontrolled forms alone - but mainly that you can build rich abstractions on top. The goal is to enable those libraries rather than having a really good outcome built-in. We have more examples and features planned for the advanced use cases too.
I think there is a typo in code example under Benefits section - it should be startTransition
instead of setIsPending
, right?
@malyzeli Thanks, fixed.
Does useActionState can be used for right now in the canary version?, i got an error in the nextjs 14
Next.js hasn't caught up with the React version that supports this hook. You need to wait for a release of https://github.com/vercel/next.js/pull/64798 to use this hook.
In the benefits part where the useActionState
Great PR and great to see how fast the team responds to the feedback! Leaving just my 2 cents here from an educational perspective:
I ran into the same confusion when I wrote my blog post about Forms in Next. Now if I understand this PR correctly,
useFormState
will go away in favor oruseActionState
, butuseFormStatus
will stay around as a more fine-grained primitive (where I didn't have any usage yet, but probably more interesting for library/framework authors).Now I have a kinda related question. In my article, I wanted to show how to trigger a reactive toast message once an action returns its response. But I had no indicator for the new
formState
, therefore I had to return atimestamp
(read:timestamp: Date.now()
) from the action asformState
, so that I could reactively show a toast message in a custom hook:import { useRef, useEffect } from 'react'; import { toast } from 'react-hot-toast'; type FormState = { message: string; fieldErrors: Record<string, string[] | undefined>; timestamp: number; }; const useToastMessage = (formState: FormState) => { const prevTimestamp = useRef(formState.timestamp); const showToast = formState.message && formState.timestamp !== prevTimestamp.current; useEffect(() => { if (showToast) { if (formState.status === 'ERROR') { toast.error(formState.message); } else { toast.success(formState.message); } prevTimestamp.current = formState.timestamp; } }, [formState, showToast]); }; export { useToastMessage };
Since the returned
message
could be the same (e.g. "Successful request.") for two successive requests, I had to introduce thetimestamp
which does the check to see whether its a new instance ofmessage
to show as toast. Otherwise the toast would have only shown once:formState.timestamp !== prevTimestamp.current
Now I see there would be a way around this with
useActionState
, e.g. checking if thepending
state goes fromtrue
tofalse
and showing the toastmessage
(if there is any in theformState
). Am I correct or is the best practice any other way? Thanks for you input! I want to showcase these use case in the best possible way :)
Excellent article you published, really a detailed way of explanation, waiting for an update. Thank you
great work. Cant wait to use it w/ NextJS. I really like that the pending is merged into one hook (apart from other great things). Came here to see if useFormState can also be triggered manually within a react-hook-form handler just to see that the next iteration is even better. One little bonus of the rename is that there is no name clash with the hook from react-hook-form anymore. I know that was not the reason but a nice sideeffect.
Thank you for adding this new hook—I'm really excited about it. I have a question regarding its functionality. Is it possible for the hook to accept a function with variadic arguments for the payload? For example, could it handle a ServerAction function designed to take multiple arguments like this?
async function serverAction(arg1, arg2, arg3) {}
Hey @sebmarkbage, thanks for getting back to me above and apologies for not replying back until now.
Before receiving your response, I created this reference repo where I highlighted the aforementioned issues in a practical example. Happy FormData
can be serialized and forms are cleared by default now, those changes isomorphic behavior a bit clearer and easier to do well.
I still don't see the purpose of the first "last state"-argument on the action handlers - anything that it does solve for me in my app can be solved by adding a hidden input, but I'm looking forward to seeing these advanced use cases. I did ask Twitter to see if anyone could give me a compelling reason why it exists, but I received no compelling responses, so I and others seem to need some education. Currently, it feels like a leaky abstraction that should be hidden from me as a user.
Also before receiving your response, I created a bastardized version of the API I suggested above in this PR of the repo above by hacking Next.js' async storage and using a global context provider.
I did it by hydrating the submitted form's values (with omitted files) and I think it's worth the trade-off, considering it also would mean each proper "with JS" submission can always return zero bytes for the previous payload since it can simply be provided by sniffing FormData
before sending it to the server (and it could include File
s there too). In the case of uncontrolled forms, my proposed API only adds extra payload for no-JS form submissions, while the current API will add extra payload to all with-JS submissions that have errors.
I see that "good forms" are per definition "controlled forms" (and for big/complex forms it'd always be the case), but if the APIs would allow it, I think uncontrolled forms could become great forms.
The APIs still leave me wanting a lil' bit more, but I'm grateful for your work and your response to this; I know there are many considerations and I know that I still might be missing important nuances. Thank you. 🙏