scrimba
What's new in React 19
useFormStatus()
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

AboutCommentsNotes
useFormStatus()
Expand for more info
index.jsx
run
preview
console
import ReactDOM from "react-dom/client"
import { useState, useActionState, useOptimistic } from "react"

import { updateNameInDB } from "./api"

function App() {
const [state, actionFunction, isPending] = useActionState(
updateName,
{
error: null,
name: JSON.parse(localStorage.getItem("name")) || "Anonymous user"
}
)

const [optimisticName, setOptimisticName] = useOptimistic(state.name)

async function updateName(prevState, formData) {
setOptimisticName(formData.get("name"))
try {
const newName = await updateNameInDB(formData.get("name"))
return { name: newName, error: null }
} catch (error) {
return { error, name: prevState.name }
}
}

return (
<>
<p className="username">
Current user: <span>{optimisticName}</span>
</p>

<form action={actionFunction}>
<input
type="text"
name="name"
required
/>
<button type="submit">Update</button>
{!isPending && state.error && <p className="error">{state.error.message}</p>}
</form>
</>
)
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />)
Console
/index.html
-4:40