scrimba
What's new in React 19
useActionState() - Part 3
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

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

function App() {

const [name, actionFunction, isPending] = useActionState(
updateName,
JSON.parse(localStorage.getItem("name")) || "Anonymous user"
)

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

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

{isPending && <p>Loading...</p>}

<form action={actionFunction}>
<input
type="text"
name="name"
required
/>
<button type="submit">Update</button>
</form>
</>
)
}

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