diff --git a/src/content/reference/react-dom/hooks/useFormStatus.md b/src/content/reference/react-dom/hooks/useFormStatus.md index 8733ec0ca69..a28e54fd25d 100644 --- a/src/content/reference/react-dom/hooks/useFormStatus.md +++ b/src/content/reference/react-dom/hooks/useFormStatus.md @@ -47,7 +47,7 @@ export default function App() { } ``` -To get status information, the `Submit` component must be rendered within a `
`. The Hook returns information like the `pending` property which tells you if the form is actively submitting. +To get status information, the `Submit` component must be rendered within a ``. The Hook returns information like the `pending` property which tells you if the form is actively submitting. In the above example, `Submit` uses this information to disable `; } @@ -165,6 +165,62 @@ function Form() { } ``` +When implementing a library or application that involve rich, complex forms, we recommend implementing a Hook similar to `useFormStatus` by using the [form onSubmit event-handler](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event) with [startTransition](/reference/react/startTransition), and (optionally) [useOptimistic](/reference/react/useOptimistic): + + + + +```js src/App.js +import { useState, startTransition, useOptimistic } from "react"; +import { addCount } from "./api"; + +export default function Form() { + const [pending, setPending] = useState(false); + const [count, setCount] = useState(0); + const [optimisticCount, optimisticIncreaseCount] = useOptimistic( + count, + (state) => state + 1 + ); + function handleSubmit(event) { + event.preventDefault(); + setPending(true); + startTransition(async () => { + optimisticIncreaseCount(); + const updatedCount = await addCount(count); + setCount(updatedCount); + setPending(false); + }); + } + return ( + +

This button has been pressed {"" + optimisticCount} times.

+ + + ); +} +``` + +```js src/api.js hidden +export async function addCount(count) { + // simulate a delay from a API/network call + await new Promise((res) => setTimeout(res, 500)); + return count + 1; +} +``` + +```json package.json hidden +{ + "dependencies": { + "react": "canary", + "react-dom": "canary", + "react-scripts": "^5.0.0" + }, + "main": "/index.js", + "devDependencies": {} +} +``` +
+ ### Read the form data being submitted {/*read-form-data-being-submitted*/} @@ -246,7 +302,7 @@ export async function submitForm(query) { "devDependencies": {} } ``` - + ---