React v19, unboxing! 📦 – DEV Community
December 24, 2024

React v19, unboxing! 📦 – DEV Community


introduce

React v19 has just been released. Today, it is one of the most popular libraries in the world, known for its simplicity and efficient DOM handling. A new edition has been launched this year and here I bring you all the news as always, with practical examples, but in Spanish 👀.


action

Actions are asynchronous transitions you make, such as calling a backend to update state. This new feature makes it easier to manage forms in React and incorporates new hooks such as useTransaction():

  • How we handled the form before:
// Before Actions
function UpdateName({}) {
  const [name, setName] = useState("");
  const [error, setError] = useState(null);
  const [isPending, setIsPending] = useState(false);

  const handleSubmit = async () => {
    setIsPending(true);
    const error = await updateName(name);
    setIsPending(false);
    if (error) {
      setError(error);
      return;
    }
    redirect("/path");
  };

  return (
    <div>
      <input value={name} onChange={(event) => setName(event.target.value)} />
      <button onClick={handleSubmit} disabled={isPending}>
        Update
      </button>
      {error && <p>{error}</p>}
    </div>
  );
}
Enter full screen mode

Exit full screen mode

  • With use useTransaction()
// Using pending state from Actions
function UpdateName({}) {
  const [name, setName] = useState("");
  const [error, setError] = useState(null);
  const [isPending, startTransition] = useTransition();

  const handleSubmit = () => {
    startTransition(async () => {
      // Esta transicion es una llamada a una API asincrona
      // Aca isPending = true
      const error = await updateName(name);
      if (error) {
        setError(error);
        return; // Aca isPending = false
      }
      redirect("/path"); // Aca isPending = false
    });
  };

  return (
    <div>
      <input value={name} onChange={(event) => setName(event.target.value)} />
      <button onClick={handleSubmit} disabled={isPending}>
        Update
      </button>
      {error && <p>{error}</p>}
    </div>
  );
}
Enter full screen mode

Exit full screen mode


new hook


Use action states

One way to simplify calls to Actions is to use new hooks useActionState

// Using 
Actions and useActionState
function ChangeName({ name, setName }) { const [error, submitAction, isPending] = useActionState( // los valores del campo son los nombres de los inputs async (previousState, formData) => { // isPending es true const error = await updateName(formData.get("name")); if (error) { return error; // esto settea el error, isPending es false } redirect("/path"); return null; // isPending es false }, null ); return ( <form action={submitAction}> <input type="text" name="name" /> <button type="submit" disabled={isPending}> Update </button> {error && <p>{error}</p>} </form> ); }
Enter full screen mode

Exit full screen mode


New hook: useOptimistic

new hook useOptimistic It is used to change the result of a value when a request is made, without waiting for the result and being optimistic about the expected result of the request.
This example shows how to set the name before making the request:

function ChangeName({ currentName, onUpdateName }) {
  const [optimisticName, setOptimisticName] = useOptimistic(currentName);

  const submitAction = async (formData) => {
    const newName = formData.get("name");
    setOptimisticName(newName); // Aca se muestra el nombre actual antes de confirmarse el cambio
    const updatedName = await updateName(newName);
    onUpdateName(updatedName); // Aca confirmamos el cambio del nombre
  };

  return (
    <form action={submitAction}>
      <p>Your name is: {optimisticName}</p>
      <p>
        <label>Change Name:</label>
        <input
          type="text"
          name="name"
          disabled={currentName !== optimisticName}
        />
      </p>
    </form>
  );
}
Enter full screen mode

Exit full screen mode


ReactDOM



action

as we are useActionStateform fields can now receive new properties, such as action and formAction, for use , y



2024-12-23 22:31:00

Leave a Reply

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