Published 28/04/2024

Exploring React 19 - What's New and Noteworthy

The React 19 Beta was released a few days ago. Let's take a look at the exciting new changes in React 19.

Actions

Actions introduce various new apis to help developers state changes. Common use cases for React apps are like forms, where a user fills up the details and submits the information to server.

useTransition & useOptimistic

In React 19, useTransition, allows the use of async functions to handle transition. When the transition is invoked, the isPending state will be updated to true and set to false when the transition ends. This helps to prevent UI blocking and allows users to continue to interact with the page.

The introduction of useOptimistic allows the developers to optimistically show the result while the async action is made in the background. When the action is completed, the optimistic value will be returned to its original state

const [optimisticName, setOptimisticName] = useOptimistic('');
const [isPending, startTransition] = useTransition();
const handleSubmit = async (formData) => {
  setOptimisticName(formData.get('name'));
  setError(false);
  startTransition(async () => {
    const error = await updateToServer(formData);
    if (error) {
      setError(error);
      return;
    }
    handleSuccess();
  });
};

References: useOptimistic, useTransition

useActionState

The introduction of useActionState allows the access to various form states from a single hook. It accepts two arguments, an function and initial state. It returns the following form states: {data, submitAction, isPending}. The submitAction is a new action function and can be passed into the <form> as an action prop.

const action = async (prevState, formData) => {
  const name = formData.get('name');
  const err = await updateToServer(name);
  if (err) return { ...prevState, err };
  return { ...prevState, name, err: false };
};
const [data, submitAction, isPending] = useActionState(action, {
  name: 'default name',
  err: false,
});

Reference: useActionState

<form>

The <form> is a new element introduced. It is compatible with the native HTML form element but also accepts actionFunction as props. The actionFunction accepts a single argument formData which allows easier construction and manipulation of data before sending it to the server.

<form action={actionFunction}>
  // your custom input fields
</form>

Reference: form

useFormStatus

Instead of prop drilling, useFormStatus hook can be called within child components of a <form>. It has access to the last submitted form state and returns the following of values:

  1. data - FormData
  2. method - form method ie "get" or "post" // defaults to get
  3. pending - pending state of the form
  4. action - action function that is passed into the form element
const FormStatusButton = () => {
  const { pending, data, method, action } = useFormStatus();
  return (
    
    <button type="submit" disabled={pending}>
      Submit
    </button>
  );
};

export const FormUseActionState = () => {
  // other logic
  return (
    <form action={submitAction}>
      <input name="name" defaultValue={data.name} />
      <FormStatusButton />
    </form>
  );
};

Reference: useFormStatus

use

Instead of useContext, the more powerful use not only allows access to context providers but also reading a Promise. However, promises created during render are not supported. Only promises in server components work.

Reference: use

context

Instead of creating a context and wrapping components with Context.Provider to access the context, we can directly use the Context.

const MyContext = createContext()

function ContextApp(children) {
  return (
    <MyContext value="any value">
      {children}
    </MyContext>
  )
}

Native support for document metadata

Previously to support the adding metadata tags like <title>, <metadata> into react components, there were libraries such as react-helmet. Otherwise, developers had to manually insert them into the html template. Now in React 19, this is natively supported. Write these tags as part of the component and React will hoist them to the <header> of the document.

function MyComponent(meta) {
  const { title, content } = meta
  return (
    <>
      <title>{title}</title>
      <meta content={content} />
      <div>
        <MyOtherReactComponent />
      </div>
    </>
  )
}

Takeaways

Here are the key takeaways from the React 19 Beta release:

  • Actions: Introduces new APIs to help manage state changes, especially useful for form submissions.
    • useTransition & useOptimistic: Allows for asynchronous transitions and optimistic updates, improving UI responsiveness.
    • useActionState: Provides a single hook to access various form states, simplifying form management.
    • <form> Element: A new element compatible with native HTML forms

These new updates and features will greatly increase the productivity of developers using React, especially when it involves the manipulation of data in forms or handling state of the forms. Custom libraries such as react-helmet that are providing can leverage on the native capabilities of React to improve on the performance of the code.

Demo: https://stackblitz.com/edit/react-19-beta-actions?file=src%2FForm.jsx

Tag
react19reactuseActionStateuseTransitionuseOptimisticuseFormStatus
Categories
Technology
contact: work[at]jianhowe.com