THE TECH PALACE / COMMUNITY

Report a comment

Tell us what needs attention. Your report is reviewed in the editorial studio.

Reason

Library / Frontend

FRONTEND

What's new with React 19?

Explore the new features of React 19: Actions, Server Components, useOptimistic to improve your web applications

Editorial readingKeep exploring
Modular components converge into a responsive tree

The world of web development is constantly evolving. React, a major player, is not left out in this progression. Its new version introduces innovative features that promise to transform the way developers design and interact with applications.

Let’s dive into the most significant advances in React 19 together.

The “Actions”

Managing data mutations has been simplified. With React 19, the introduction of Actions revolutionizes this approach. Now developers can use asynchronous functions within transitions to automatically handle wait states, errors, forms, and optimistic updates.

import { useTransition } from 'react';

function UpdateName() {
  const [name, setName] = useState("");
  const [error, setError] = useState(null);
  const [isPending, startTransition] = useTransition();

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

  return (
    <div>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={handleSubmit} disabled={isPending}>
        Mettre à jour
      </button>
      {error && <p>{error}</p>}
    </div>
  );
}

*In this example, startTransition handles the wait state while the name is updating, thereby improving the user experience by making the interface more responsive.

Server Components

Server Components are a major advancement, allowing components to be rendered on the server side before sending them to the client. This approach reduces the amount of JavaScript sent to the browser, improving initial load times and search engine optimization (SEO).

Benefits of Server Components:

  • Performance improvement: Reduced client-side JavaScript.

  • Better SEO: Pre-rendered content accessible to search engines.

  • Code portability: Simplified sharing of logic between server and client.

New Hook: useOptimistic

The useOptimistic hook introduced in React 19 makes it easier to manage optimistic updates. It allows the expected final state to be immediately displayed during an asynchronous data mutation, providing a smoother user experience.

import { useOptimistic } from 'react';

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

  const handleSubmit = async (newName) => {
    setOptimisticName(newName);
    const error = await onUpdateName(newName);
    if (error) {
      setOptimisticName(currentName); // Revert in case of error
    }
  };

  return (
    <div>
      <p>Nom : {optimisticName}</p>
      <button onClick={() => handleSubmit("Nouveau Nom")}>Changer le nom</button>
    </div>
  );
}

Here, useOptimistic allows the user interface to be immediately updated while waiting for confirmation from the server, thus improving the responsiveness of the application.

API use

React 19 introduces the use API, which allows reading asynchronous resources directly during rendering. By calling use with a promise, React pauses rendering until the promise is resolved, simplifying loading state management.

import { use } from 'react';

function Comments({ commentsPromise }) {
  const comments = use(commentsPromise);

  return (
    <div>
      {comments.map((comment) => (
        <p key={comment.id}>{comment.text}</p>
      ))}
    </div>
  );
}

In this example, use suspends rendering of component Comments until commentsPromise is resolved, ensuring that data is available before rendering.

Reference Improvements (Refs)

Reference management has been simplified in React 19. Now refs can be passed directly as props to functional components, eliminating the need to use forwardRef. Additionally, it is possible to define a cleanup function that runs when the element is removed from the DOM.

const Button = ({ ref, children }) => (
  <button ref={ref}>
    {children}
  </button>
);

This approach makes the code more readable and reduces complexity when handling refs.

Style sheet management

React 19 improves the management of style sheets by allowing you to specify the priority (precedence) of styles. This ensures that styles are loaded in the correct order, improving the visual consistency of the application.

function ComponentOne() {
  return (
    <div>
      <link rel="stylesheet" href="styles.css" precedence="high" />
      {/* Contenu du composant */}
    </div>
  );
}

By setting the precedence property, React ensures that styles are applied in the desired order, avoiding potential conflicts.*

Conclusion

React 19 brings a range of innovative features that simplify development and improve application performance. This release provides developers with powerful tools to create ever smoother and more responsive user experiences.


Sources used for this article

This article has been written using official information and reliable resources to ensure accurate and up-to-date content:

More ideas to explore.

The conversation

Share your view. Messages with links or suspicious content are reviewed before they appear.