Unverified Commit 82928808 authored by Joseph's avatar Joseph Committed by GitHub

docs: amends to preserving-ui-state guide (#92270)

Still drafting this one. We want to show good patterns, and effects are
often a last resource. We favor here resetting in an event handler.
parent 7f8ba2dc
...@@ -140,95 +140,114 @@ function ProductTab() { ...@@ -140,95 +140,114 @@ function ProductTab() {
With this approach, `isDialogOpen` derives from the URL rather than component state. When navigating away and returning, the search param is cleared (the URL changed), so `isDialogOpen` becomes `false`. Opening the dialog sets the param, which changes `isDialogOpen` and triggers the Effect. With this approach, `isDialogOpen` derives from the URL rather than component state. When navigating away and returning, the search param is cleared (the URL changed), so `isDialogOpen` becomes `false`. Opening the dialog sets the param, which changes `isDialogOpen` and triggers the Effect.
### Form input values ### Forms, inputs, and state
Activity preserves form input values: text typed into fields, selected options, checkbox states. Activity preserves form input values (text fields, selected options, checkbox states), submission results, and status messages across navigations.
**When to keep it:** A search page with filters, a draft the user was composing, or a settings form with unsaved changes. Preserving input state is one of the biggest UX wins because the user doesn't lose work. **When to keep it:** A search page with filters, a draft the user was composing, or a settings form with unsaved changes. Preserving input state is one of the biggest UX wins because the user doesn't lose work.
**When to reset it:** A "create new item" page where returning should start fresh, or a contact form after successful submission. **When to reset it:** A "new transaction" flow where each visit should start fresh, or a form where stale success/error messages would be confusing in a new context.
To reset form fields when Activity hides the component, use a callback ref: #### Resetting form state on submit
```tsx Consider a page where the user creates a new item. After submitting, `router.push` navigates to the new record. Since Activity preserves the page, navigating back shows the previous name still in the form. Reset state in the event handler to keep the form fresh:
<form
ref={(form) => {
// Cleanup function - runs when Activity hides this component
return () => form?.reset()
}}
>
{/* fields */}
</form>
```
This resets the form whenever the user navigates away. ```tsx filename="app/new/page.tsx" highlight={13}
'use client'
### Action state (`useActionState`) import { useState } from 'react'
import { useRouter } from 'next/navigation'
Activity preserves [`useActionState`](https://react.dev/reference/react/useActionState) results: success messages, error messages, and any other state returned by the action. export default function NewItemPage() {
const [name, setName] = useState('')
const router = useRouter()
**When to keep it:** A ticket redemption form showing "Ticket redeemed successfully", or a settings form showing "Changes saved". Seeing the result of a previous action when returning to the page is useful confirmation so the user can see what happened. async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
const item = await createItem({ name })
setName('')
router.push(`/items/${item.id}`)
}
**When to reset it:** A "new transaction" flow where each visit should start fresh, or a form where stale success/error messages would be confusing in a new context. return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Create</button>
</form>
)
}
```
You can think of `useActionState` as a `useReducer` that allows side effects. It doesn't have to only handle form submissions; you can dispatch any action to it. Adding a `RESET` action gives you a clean way to clear state when Activity hides the component (see [Reset state](https://react.dev/reference/react/useActionState#reset-state) in the React docs): #### Resetting stale status messages
```tsx highlight={5-6,9-21,26-35} If after submitting you set a status into state to render a feedback message, there's often not a reliable user-initiated event to clear it.
'use client'
import { useActionState, useLayoutEffect, useRef, startTransition } from 'react' The user might navigate via `next/link` elements out of your control, or via browser controls.
type Action = { type: 'SUBMIT'; data: FormData } | { type: 'RESET' } Navigating back to the form shows a stale message. In this case, you may use a `useLayoutEffect` cleanup to reset the form and state:
type State = { success: boolean; error: string | null }
function CommentForm() { ```tsx highlight={17-26}
const [state, dispatch, isPending] = useActionState( 'use client'
async (prev: State, action: Action) => {
if (action.type === 'RESET') { import { useState, useRef, useLayoutEffect } from 'react'
return { success: false, error: null }
}
// Handle the form submission
const res = await saveComment(action.data)
if (!res.ok) return { success: false, error: res.message }
shouldReset.current = true
return { success: true, error: null }
},
{ success: false, error: null }
)
function ContactForm() {
const [name, setName] = useState('')
const [status, setStatus] = useState<'idle' | 'success'>('idle')
const shouldReset = useRef(false) const shouldReset = useRef(false)
// Dispatch RESET when Activity hides this component async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
await sendMessage({ name })
setStatus('success')
shouldReset.current = true
}
// Reset stale success message when Activity hides this component
useLayoutEffect(() => { useLayoutEffect(() => {
return () => { return () => {
if (shouldReset.current) { if (shouldReset.current) {
shouldReset.current = false shouldReset.current = false
startTransition(() => { setStatus('idle')
dispatch({ type: 'RESET' }) setName('')
})
} }
} }
}, [dispatch]) }, [])
return ( return (
<form action={(formData) => dispatch({ type: 'SUBMIT', data: formData })}> <form onSubmit={handleSubmit}>
<textarea name="comment" /> <input value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit" disabled={isPending}> <button type="submit">Send</button>
{isPending ? 'Posting...' : 'Post Comment'} {status === 'success' && <p>Message sent!</p>}
</button>
{state.success && <p>Comment posted!</p>}
{state.error && <p>{state.error}</p>}
</form> </form>
) )
} }
``` ```
Here's what happens step by step: The `shouldReset` ref ensures the cleanup only runs after a successful submission. If the user navigates away mid-draft without submitting, their input is preserved.
If you use [`useActionState`](https://react.dev/reference/react/useActionState), the same approach applies. See [Reset state](https://react.dev/reference/react/useActionState#reset-state) in the React docs for how to add a `RESET` action to your reducer.
<details>
<summary>Resetting all form fields with a callback ref</summary>
You can use a callback ref to call `form.reset()` when Activity hides the component:
```tsx
<form
ref={(form) => {
return () => form?.reset()
}}
>
<input name="email" />
<input name="message" />
<button type="submit">Send</button>
</form>
```
This resets all fields whenever the user navigates away.
1. The user submits the form. The reducer receives a `SUBMIT` action with the `FormData`, calls `saveComment`, and returns `{ success: true }`. It also sets `shouldReset.current = true` to mark that a reset is needed. </details>
2. The user navigates away. Activity hides the component and runs the `useLayoutEffect` cleanup. Because `shouldReset.current` is `true`, it dispatches a `RESET` action.
3. The reducer receives `RESET` and returns the initial state (`{ success: false, error: null }`). The stale success message is cleared.
4. If the user navigates back, the form is ready for a new submission. If they never submitted (step 1 didn't happen), `shouldReset.current` is still `false`, so no `RESET` is dispatched. The form stays as-is.
## State and authentication ## State and authentication
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment