React 19 Actions – Simplify Kind Submission and Loading States


React 19 introduces Actions, that are asynchronous capabilities. Actions are useful in making type submissions simpler. This tutorial dives into what Actions are and how you can use them.

You will study:

  1. The brand new React 19 characteristic, Actions
  2. The brand new React 19 hooks, useActionState and useFormStatus
  3. convert a React 18 type to a React 19 type

Function: React Actions

To know Actions, let’s first check out how we handle kinds in the present day. In React 18 and earlier, we submit kinds utilizing the handleSubmit operate in a button. Here is a easy type that has one enter area identify:

// Kind submission in React 18
console.data('React 18 type');

const [name, setName] = useState('');
const [isPending, setIsPending] = useState(false);

const handleChange = (occasion) => {
  setName(occasion.goal.worth);
};

const handleSubmit = (occasion) => {
  occasion.preventDefault();
  setIsPending(true);
  setTimeout(() => {
    // name API
    setIsPending(false);
  }, 500);
};

return (
  <type>
    <enter sort="textual content" identify="identify" onChange={handleChange} />
    {isPending ? <p>Loading...</p> : <p>Hi there in React 18, {identify}</p>}
    <button onClick={handleSubmit} disabled={isPending}>
      Replace
    </button>
  </type>
);

On this code, we’re doing the next:

  1. Including a loading state: We use a variable isPending to manually hold observe of the loading state.
  2. Kind submission: The shape is submitted utilizing the handleSubmit occasion handler connected to the onClick occasion of the button.
  3. Capturing the submitted worth: The handleChange operate captures the submitted worth and shops it in state variables.

What Are React Actions?

With React 19, dealing with kinds turns into simpler with Actions, impressed by frameworks akin to Remix. One key characteristic is the improved use of startTransition to handle pending states.

startTransition was launched in React 18, permitting builders to mark sure updates as much less pressing.

In React 19, startTransition can now deal with async capabilities, making it much more highly effective for managing asynchronous duties and enhancing the consumer expertise throughout type submissions.

const [isPending, startTransition] = useTransition();

const handleSubmit = () => {
  startTransition(async () => {
    const error = await updateName(identify);
    if (error) {
      setError(error);
      return;
    }
    redirect('/path');
  });
};

This async operate inside startTransition is named an Motion. What makes actions cool is that they can be utilized on to submit kinds like so:

<type motion="{actionFn}">...</type>

This format might look acquainted if you’re skilled with PHP.

Create a React Motion

To create an async operate, we are able to use a brand new hook launched in React 19 known as useActionState. We name this hook and go in an motion operate and an preliminary state. This hook returns the up to date state and a type motion actionFn, which can be utilized to wire up a type.

const [state, actionFn] = useActionState(submitAction, { identify: '' });

Now with this wired up with the shape, we now have the next:

<type motion={actionFn}>
  <enter sort="textual content" identify="identify" />

  <button sort="submit" disabled="{pending}">
    Replace
  </button>
</type>

So as to add a loading state, we are able to use a brand new hook launched in React 19 known as useFormStatus.

const { pending, information, technique, motion } = useFormStatus();

This hook gives info on the standing of the shape. The pending state signifies whether or not the shape is being submitted, and information is a FormData object containing the submitted information. We use this pending state to indicate a loader.

However there’s one caveat: this hook can solely be utilized in a toddler part, not within the type itself. So, we now have to create little one parts SubmitButton and Loader to retrieve a pending state:

operate Loader() {
  const { pending } = useFormStatus();
  return <div>{pending && "Loading..."}</div>;
}

operate SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button sort="submit" disabled={pending}>
      Replace
    </button>
  );
}

....

return(
<type motion={formAction}>
      <enter sort="textual content" identify="identify" />
      <Loader />
      <SubmitButton />
    </type>
)

We are able to additionally seize helpful details about the information submitted to the shape by retrieving it from the state returned from useActionState.

const [state, formAction] = useActionState(submitAction, { identify: '' });

So this is the ultimate type:

operate Loader() {
  const { pending } = useFormStatus();
  return <div>{pending && 'Loading...'}</div>;
}

operate SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button sort="submit" disabled={pending}>
      Replace
    </button>
  );
}

operate Title({ identify }) {
  return <p>Hi there in 19 {identify}</p>;
}

operate App() {
  console.data('React 19 type');

  const [state, formAction] = useActionState(submitAction, { identify: '' });

  return (
    <type motion={formAction}>
      <enter sort="textual content" identify="identify" />
      <Loader />
      <SubmitButton />
      <Title identify={state?.identify} />
    </type>
  );
}

Examine this with the React 18 type on the prime of this submit to verify the distinction.

Conclusion

By using actions together with hooks like useActionState and useFormStatus, we are able to simply handle type states, seize submitted information, and supply responsive suggestions to customers throughout type submissions to indicate pending states.

I’m excited for this improved expertise of dealing with kinds in React 19, and I look ahead to eradicating pointless handleSubmits, useStates, and pending states.

In my subsequent article, I’ll focus on one other thrilling new React characteristic: the React Compiler. This software mechanically memoizes, eliminating the necessity for useMemo and useCallback. Keep up to date and get the article instantly in your inbox by becoming a member of my e-newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *