-
Notifications
You must be signed in to change notification settings - Fork 47k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add React.useActionState
#28491
Add React.useActionState
#28491
Conversation
1d4e7f9
to
8fd1e99
Compare
In your PR description, what is the |
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? |
54ab3ab
to
651adba
Compare
@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 |
In case anyone is reading the PR description examples and wondering (like I did) what types the first returned array element can be ( It looks like the first argument is just react/packages/react-debug-tools/src/ReactDebugHooks.js Lines 656 to 659 in 651adba
Also confirmed over here:
Source: https://twitter.com/rickhanlonii/status/1765592038026641571 |
Thanks @karlhorky, I added the type to the reference section, updated the code examples to use |
): [Awaited<S>, (P) => void, boolean] { | ||
currentHookNameInDev = 'useActionState'; | ||
mountHookTypesDev(); | ||
return mountFormState(action, initialState, permalink); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: Let's rename these to "action state" since the form state ones will go away eventually
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm going to do that in a follow up, it was in the original version but the PR was too big, so I'm splitting it out. Wanted to get this reviewed before submitting that to avoid annoying conflicts.
651adba
to
435e9b3
Compare
435e9b3
to
a31a3df
Compare
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, 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
Since the returned
Now I see there would be a way around this with |
🥳 . All makes sense. Appreciate your responses here. I'll elaborate more on the
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:
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
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 |
Something went wrong when rebasing #28491 and renaming the hook.
- facebook/react#28596 - facebook/react#28625 - facebook/react#28616 - facebook/react#28491 - facebook/react#28583 - facebook/react#28427 - facebook/react#28613 - facebook/react#28599 - facebook/react#28611 - facebook/react#28610 - facebook/react#28606 - facebook/react#28598 - facebook/react#28549 - facebook/react#28557 - facebook/react#28467 - facebook/react#28591 - facebook/react#28459 - facebook/react#28590 - facebook/react#28564 - facebook/react#28582 - facebook/react#28579 - facebook/react#28578 - facebook/react#28521 - facebook/react#28550 - facebook/react#28576 - facebook/react#28577 - facebook/react#28571 - facebook/react#28572 - facebook/react#28560 - facebook/react#28569 - facebook/react#28573 - facebook/react#28546 - facebook/react#28568 - facebook/react#28562 - facebook/react#28566 - facebook/react#28565 - facebook/react#28559 - facebook/react#28508 - facebook/react#20432 - facebook/react#28555 - facebook/react#24730 - facebook/react#28472 - facebook/react#27991 - facebook/react#28514 - facebook/react#28548 - facebook/react#28526 - facebook/react#28515 - facebook/react#28533 - facebook/react#28532 - facebook/react#28531 - facebook/react#28407 - facebook/react#28522 - facebook/react#28538 - facebook/react#28509 - facebook/react#28534 - facebook/react#28527 - facebook/react#28528 - facebook/react#28519 - facebook/react#28411 - facebook/react#28520 - facebook/react#28518 - facebook/react#28493 - facebook/react#28504 - facebook/react#28499 - facebook/react#28501 - facebook/react#28496 - facebook/react#28471 - facebook/react#28351 - facebook/react#28486 - facebook/react#28490 - facebook/react#28488 - facebook/react#28468 - facebook/react#28321 - facebook/react#28477 - facebook/react#28479 - facebook/react#28480 - facebook/react#28478 - facebook/react#28464 - facebook/react#28475 - facebook/react#28456 - facebook/react#28319 - facebook/react#28345 - facebook/react#28337 - facebook/react#28335 - facebook/react#28466 - facebook/react#28462 - facebook/react#28322 - facebook/react#28444 - facebook/react#28448 - facebook/react#28449 - facebook/react#28446 - facebook/react#28447 - facebook/react#24580 - facebook/react#28514 - facebook/react#28548 - facebook/react#28526 - facebook/react#28515 - facebook/react#28533 - facebook/react#28532 - facebook/react#28531 - facebook/react#28407 - facebook/react#28522 - facebook/react#28538 - facebook/react#28509 - facebook/react#28534 - facebook/react#28527 - facebook/react#28528 - facebook/react#28519 - facebook/react#28411 - facebook/react#28520 - facebook/react#28518 - facebook/react#28493 - facebook/react#28504 - facebook/react#28499 - facebook/react#28501 - facebook/react#28496 - facebook/react#28471 - facebook/react#28351 - facebook/react#28486 - facebook/react#28490 - facebook/react#28488 - facebook/react#28468 - facebook/react#28321 - facebook/react#28477 - facebook/react#28479 - facebook/react#28480 - facebook/react#28478 - facebook/react#28464 - facebook/react#28475 - facebook/react#28456 - facebook/react#28319 - facebook/react#28345 - facebook/react#28337 - facebook/react#28335 - facebook/react#28466 - facebook/react#28462 - facebook/react#28322 - facebook/react#28444 - facebook/react#28448 - facebook/react#28449 - facebook/react#28446 - facebook/react#28447 - facebook/react#24580
- facebook/react#28596 - facebook/react#28625 - facebook/react#28616 - facebook/react#28491 - facebook/react#28583 - facebook/react#28427 - facebook/react#28613 - facebook/react#28599 - facebook/react#28611 - facebook/react#28610 - facebook/react#28606 - facebook/react#28598 - facebook/react#28549 - facebook/react#28557 - facebook/react#28467 - facebook/react#28591 - facebook/react#28459 - facebook/react#28590 - facebook/react#28564 - facebook/react#28582 - facebook/react#28579 - facebook/react#28578 - facebook/react#28521 - facebook/react#28550 - facebook/react#28576 - facebook/react#28577 - facebook/react#28571 - facebook/react#28572 - facebook/react#28560 - facebook/react#28569 - facebook/react#28573 - facebook/react#28546 - facebook/react#28568 - facebook/react#28562 - facebook/react#28566 - facebook/react#28565 - facebook/react#28559 - facebook/react#28508 - facebook/react#20432 - facebook/react#28555 - facebook/react#24730 - facebook/react#28472 - facebook/react#27991 - facebook/react#28514 - facebook/react#28548 - facebook/react#28526 - facebook/react#28515 - facebook/react#28533 - facebook/react#28532 - facebook/react#28531 - facebook/react#28407 - facebook/react#28522 - facebook/react#28538 - facebook/react#28509 - facebook/react#28534 - facebook/react#28527 - facebook/react#28528 - facebook/react#28519 - facebook/react#28411 - facebook/react#28520 - facebook/react#28518 - facebook/react#28493 - facebook/react#28504 - facebook/react#28499 - facebook/react#28501 - facebook/react#28496 - facebook/react#28471 - facebook/react#28351 - facebook/react#28486 - facebook/react#28490 - facebook/react#28488 - facebook/react#28468 - facebook/react#28321 - facebook/react#28477 - facebook/react#28479 - facebook/react#28480 - facebook/react#28478 - facebook/react#28464 - facebook/react#28475 - facebook/react#28456 - facebook/react#28319 - facebook/react#28345 - facebook/react#28337 - facebook/react#28335 - facebook/react#28466 - facebook/react#28462 - facebook/react#28322 - facebook/react#28444 - facebook/react#28448 - facebook/react#28449 - facebook/react#28446 - facebook/react#28447 - facebook/react#24580
@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 Therefore, it seems like it's better to stay with the model where previous state is returned from There are a couple of things we can do to improve that experience though:
This mode is still opt-in though in that by default the form would not preserve user state unless you passed it through 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 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 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. |
## 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` to `useActionState` - 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: ```ts 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`: ```js 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): ```js 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: ```js 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: ```js 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`: ```js 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: ```js 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 (facebook#27980 (comment)) and [Allan Lasser](https://allanlasser.com/posts/2024-01-26-avoid-using-reacts-useformstatus) for their feedback and suggestions on `useFormStatus` hook.
Something went wrong when rebasing facebook#28491 and renaming the hook.
## 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` to `useActionState` - 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: ```ts 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`: ```js 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): ```js 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: ```js 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: ```js 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`: ```js 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: ```js 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 (#27980 (comment)) and [Allan Lasser](https://allanlasser.com/posts/2024-01-26-avoid-using-reacts-useformstatus) for their feedback and suggestions on `useFormStatus` hook. DiffTrain build for commit 5c65b27.
### React upstream changes - facebook/react#28643 - facebook/react#28628 - facebook/react#28361 - facebook/react#28513 - facebook/react#28299 - facebook/react#28617 - facebook/react#28618 - facebook/react#28621 - facebook/react#28614 - facebook/react#28596 - facebook/react#28625 - facebook/react#28616 - facebook/react#28491 - facebook/react#28583 - facebook/react#28427 - facebook/react#28613 - facebook/react#28599 - facebook/react#28611 - facebook/react#28610 - facebook/react#28606 - facebook/react#28598 - facebook/react#28549 - facebook/react#28557 - facebook/react#28467 - facebook/react#28591 - facebook/react#28459 - facebook/react#28590 - facebook/react#28564 - facebook/react#28582 - facebook/react#28579 - facebook/react#28578 - facebook/react#28521 - facebook/react#28550 - facebook/react#28576 - facebook/react#28577 - facebook/react#28571 - facebook/react#28572 - facebook/react#28560 - facebook/react#28569 - facebook/react#28573 - facebook/react#28546 - facebook/react#28568 - facebook/react#28562 - facebook/react#28566 - facebook/react#28565 - facebook/react#28559 - facebook/react#28508 - facebook/react#20432 - facebook/react#28555 - facebook/react#24730 - facebook/react#28472 - facebook/react#27991 - facebook/react#28514 - facebook/react#28548 - facebook/react#28526 - facebook/react#28515 - facebook/react#28533 - facebook/react#28532 - facebook/react#28531 - facebook/react#28407 - facebook/react#28522 - facebook/react#28538 - facebook/react#28509 - facebook/react#28534 - facebook/react#28527 - facebook/react#28528 - facebook/react#28519 - facebook/react#28411 - facebook/react#28520 - facebook/react#28518 - facebook/react#28493 - facebook/react#28504 - facebook/react#28499 - facebook/react#28501 - facebook/react#28496 - facebook/react#28471 - facebook/react#28351 - facebook/react#28486 - facebook/react#28490 - facebook/react#28488 - facebook/react#28468 - facebook/react#28321 - facebook/react#28477 - facebook/react#28479 - facebook/react#28480 - facebook/react#28478 - facebook/react#28464 - facebook/react#28475 - facebook/react#28456 - facebook/react#28319 - facebook/react#28345 - facebook/react#28337 - facebook/react#28335 - facebook/react#28466 - facebook/react#28462 - facebook/react#28322 - facebook/react#28444 - facebook/react#28448 - facebook/react#28449 - facebook/react#28446 - facebook/react#28447 - facebook/react#24580 - facebook/react#28514 - facebook/react#28548 - facebook/react#28526 - facebook/react#28515 - facebook/react#28533 - facebook/react#28532 - facebook/react#28531 - facebook/react#28407 - facebook/react#28522 - facebook/react#28538 - facebook/react#28509 - facebook/react#28534 - facebook/react#28527 - facebook/react#28528 - facebook/react#28519 - facebook/react#28411 - facebook/react#28520 - facebook/react#28518 - facebook/react#28493 - facebook/react#28504 - facebook/react#28499 - facebook/react#28501 - facebook/react#28496 - facebook/react#28471 - facebook/react#28351 - facebook/react#28486 - facebook/react#28490 - facebook/react#28488 - facebook/react#28468 - facebook/react#28321 - facebook/react#28477 - facebook/react#28479 - facebook/react#28480 - facebook/react#28478 - facebook/react#28464 - facebook/react#28475 - facebook/react#28456 - facebook/react#28319 - facebook/react#28345 - facebook/react#28337 - facebook/react#28335 - facebook/react#28466 - facebook/react#28462 - facebook/react#28322 - facebook/react#28444 - facebook/react#28448 - facebook/react#28449 - facebook/react#28446 - facebook/react#28447 - facebook/react#24580
@malyzeli Thanks, fixed. |
Next.js hasn't caught up with the React version that supports this hook. You need to wait for a release of vercel/next.js#64798 to use this hook. |
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. 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 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 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. 🙏 |
Overview
Depends on #28514
This PR adds a new React hook called
useActionState
to replace and improve the ReactDOMuseFormState
hook.Motivation
This hook intends to fix some of the confusion and limitations of the
useFormState
hook.The
useFormState
hook is only exported from theReactDOM
package and implies that it is used only for the state of<form>
actions, similar touseFormStatus
(which is only for<form>
element status). This leads to understandable confusion about whyuseFormState
does not provide apending
state value likeuseFormStatus
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 touseFormState
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 returnedaction
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 onlyreact-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:
useFormState
touseActionState
pending
state to the returned tuple'react'
packageReference
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 optionalinitialState
value used for the initial render, and an optionalpermalink
argument for renderer specific pre-hydration handling (such as a URL to support progressive hydration inreact-dom
).Type:
The hook returns a tuple with:
state
: the last state the action returneddispatch
: the method to call to dispatch the wrapped actionpending
: the pending state of the action and any state updates containedNotably, 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 touseFormState
:But it doesn't need to be used with a
<form/>
(neither diduseFormState
, hence the confusion):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:
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 touseTransition
. 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 byuseActionState
. 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:
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
:For greater control, you can also wrap both in a transition and use the
isPending
state of the transition:A similar technique using
useOptimistic
is preferred over usinguseTransition
directly, and is left as an exercise to the reader.Thanks
Thanks to @ryanflorence @mjackson @wesbos (#27980 (comment)) and Allan Lasser for their feedback and suggestions on
useFormStatus
hook.