SkillPilotAI

React 19 hooks

React 19 adds Actions and a set of hooks around them: useActionState, useFormStatus and useOptimistic for forms and instant UI, use() for reading promises and context, and useTransition/useDeferredValue for keeping the UI responsive during slow updates.

39.1 The problem: the button gets stuck

  • The pre-React 19 way: separate msg and busy states, handleSubmit calls preventDefault, sets busy, awaits applyCoupon, then sets msg and busy back.
  • If the network fails, the lines after await never run and the button stays stuck on Applying... (disabled).
React (JSX)
function CouponForm() {  const [msg, setMsg] = useState("");  const [busy, setBusy] = useState(false);   async function handleSubmit(e) {    e.preventDefault();    setBusy(true);    const code = e.target.elements.code.value;    setMsg(await applyCoupon(code));    setBusy(false);  }  // return: form + button disabled={busy}}
Output
Input: SAVE10   [button] Apply-- submit --[button] Applying... (disabled)-- success --[button] Apply   10% off applied-- network fails --[button] Applying... (disabled)Console: Uncaught (in promise) Error: Network error

39.2 Why are Actions used?

  • Every form manages pending, error and result by hand; miss one step and the UI gets stuck in the wrong state.
  • React 19 Action: an async function passed to a form's action prop.
  • React gives it the form data, tracks pending for you and updates the UI with the result when it finishes.
How a form Action runs
  1. 1.User submits <form action={formAction}>

  2. 2.React calls apply(prevMsg, formData)

  3. 3.isPending = true while the action runs

  4. 4.Action returns a value (or a friendly error message)

  5. 5.Return value becomes the new msg, isPending = false

Action = an async function React manages

39.3 Fix: an action function

  • apply receives the previous message and formData: no preventDefault, no reading the input by hand.
  • formData.get("code") gives the code; errors are caught and turned into a friendly message.
  • Whatever the function returns becomes the next message.
JavaScript
async function apply(prevMsg, formData) {  const code = formData.get("code");  try {    return await applyCoupon(code);  } catch {    return "Network error, try again";  }}

39.4 useActionState

  • useActionState(apply, "") takes the action and the initial message.
  • Returns three things: the current msg, formAction (for the form's action prop) and isPending (managed by React).
  • Clicking Apply disables the button immediately; the message shows on response, and on a network failure the button comes back enabled.
React (JSX)
function CouponForm() {  const [msg, formAction, isPending] =    useActionState(apply, "");   return (    <form action={formAction}>      <input name="code" />      <button disabled={isPending}>        Apply      </button>      <p>{msg}</p>    </form>  );}
Output
Input: SAVE10   [button] Apply-- submit --[button] Apply (disabled)-- success --[button] Apply   10% off applied-- network fails --[button] Apply   Network error, try again

39.5 useFormStatus

  • For a separate, reusable submit button that needs to know whether its form is submitting.
  • Imported from react-dom; gives pending, which is true while the action runs.
  • Condition: the button must be rendered inside the form whose status you need.
React (JSX)
import { useFormStatus } from "react-dom"; function SubmitButton() {  const { pending } = useFormStatus();  return (    <button disabled={pending}>      {pending ? "Applying..." : "Apply"}    </button>  );} // inside the form:// <SubmitButton />
Output
[button] Apply-- submitting --[button] Applying... (disabled)

39.6 useOptimistic

  • Optimistic update: like Instagram's heart turning red the moment you tap, without waiting for the server.
  • useOptimistic(likes, (n) => n + 1) takes the real value and an update function.
  • In likeAction, addLike() runs first so the screen shows 11 instantly; when the server saves, the real likes also become 11.
  • If saveLike returns false, the button shows 11 then goes back to 10: when the action finishes React drops the optimistic value and shows the real one, so it rolls back automatically.
React (JSX)
function LikeButton() {  const [likes, setLikes] = useState(10);  const [shown, addLike] =    useOptimistic(likes, (n) => n + 1);  async function likeAction() {    addLike();    const ok = await saveLike();    if (ok) setLikes((l) => l + 1);  }  return (    <form action={likeAction}>      <button>Likes: {shown}</button>    </form>  );}
Output
[button] Likes: 10-- click (instant) --[button] Likes: 11-- server saved --[button] Likes: 11
Output
[button] Likes: 10-- click (instant) --[button] Likes: 11-- saveLike() returned false --[button] Likes: 10
useOptimistic with rollback
  1. 1.likes = 10, shown = 10

  2. 2.Click: addLike() -> shown = 11 instantly

  3. 3.saveLike() runs in the background

  4. 4.Success: setLikes(11) -> shown stays 11

  5. 5.Failure: action ends, optimistic value dropped -> shown = 10

No manual undo needed

39.7 use(): reading a promise

  • use reads the value of a promise or a context.
  • Orders calls use(ordersPromise) and waits until the data arrives; the outer Suspense shows Loading... meanwhile, then Orders: 3.
  • Create the promise once outside the component; creating it in render makes a new promise every render.
  • Unlike other hooks, use can be called inside an if.
React (JSX)
import { use, Suspense } from "react";const ordersPromise = fetchOrders(); function Orders() {  const orders = use(ordersPromise);  return <p>Orders: {orders.length}</p>;} function App() {  return (    <Suspense fallback={<p>Loading...</p>}>      <Orders />    </Suspense>  );}
Output
Loading...Orders: 3

39.8 useDeferredValue and useTransition

  • A big, slow list under a search box renders on every key press and typing lags.
  • useDeferredValue(text) makes a deferred copy that goes to SlowList: the input always shows the latest text while the list runs a little behind in the background.
  • If you own the setter, useTransition does the same: wrap setText in startTransition.
React (JSX)
function Search() {  const [text, setText] = useState("");  const deferredText = useDeferredValue(text);   function onType(e) {    setText(e.target.value);  }  return (    <>      <input value={text} onChange={onType} />      <SlowList query={deferredText} />    </>  );}
Output
Input: sh    Results: shoes, shirt, shortsInput: sho   Results: shoes, shirt, shorts   (list still behind)Input: sho   Results: shoes, shorts          (list caught up)

39.9 Which hook when

NeedHookImport from
Form result + pendinguseActionStatereact
Form status inside a submit buttonuseFormStatusreact-dom
Show the UI update before the server respondsuseOptimisticreact
Read a promise or context (even inside an if)usereact
Slow update you trigger with your own setteruseTransitionreact
Slow update when you only get a value (e.g. a prop)useDeferredValuereact

39.10 Common mistakes

  • Calling useFormStatus in the same component that renders the form: pending is always false, because it reads only the status of its parent form.
  • Fix: move the button into a separate SubmitButton component rendered inside the form.
React (JSX)
// Wrong: useFormStatus in the component that renders the form -> pending always falsefunction CouponForm() {  const [msg, formAction] =    useActionState(apply, "");  const { pending } = useFormStatus();  return (    <form action={formAction}>      <button disabled={pending}>        {pending ? "Applying..." : "Apply"}      </button>    </form>  );}
React (JSX)
// Right: SubmitButton (which calls useFormStatus) rendered inside the formfunction CouponForm() {  const [msg, formAction] =    useActionState(apply, "");  return (    <form action={formAction}>      <SubmitButton />    </form>  );}
  • Myth: "these hooks are only for Next.js / server components". useActionState, useOptimistic and use work in a normal Vite client app; server actions just make them more powerful.
  • Old tutorials show useFormState: its new name is useActionState.

39.11 Interview tips

  • useTransition and useDeferredValue both mark an update as low priority so the UI stays responsive.
  • useTransition: you own the state setter and wrap the update in startTransition.
  • useDeferredValue: you only have a value (like a prop) and React gives you a lagging copy.
  • In React 19 transitions accept async functions, and Actions are built on top of that.