Codementor Events

React 19: Features you need to know

Published May 23, 2024
React 19:  Features you need to know

Introduction

React 19 emerges as a game-changer in front-end development, introducing many innovative features. From refined concurrent rendering to novel state-handling mechanisms, React 19 enhances both performance and developer experience. In this article, we explore these cutting-edge additions, providing insights into how they reshape the landscape of dynamic user interface development. Whether you're a seasoned React developer or new to the framework, understanding React 19's advancements is crucial for staying ahead in modern web development. Join us on a journey to unravel the transformative features that make React 19 a milestone release, setting the stage for the future of front-end innovation.

New features

  • React compilier
    React Compiler, no longer a research project, is now powering Instagram.com in production, representing a significant advancement in React's capabilities. It addresses the issue of excessive re-renders on state changes by introducing an optimizing compiler. Unlike manual memoization, this compiler automatically re-renders specific UI parts when the state changes, eliminating code clutter. Operating within the rules of both JavaScript and React, it ensures safety and performance. Developers can validate their code with tools like Strict Mode and React's ESLint plugin. The compiler is already active on Instagram.com and is set for further integration across Meta surfaces, with plans for an open-source release.
  • Actions
    In React applications, a typical scenario involves performing a data mutation and updating the state accordingly. For instance, when a user submits a form to change their name, an API request is made, and the response is then managed. Traditionally, this process required manually handling pending states, errors, optimistic updates, and sequential requests.
// Before React 19 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>
  );
}

// Using pending state from Actions
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={(event) => setName(event.target.value)} />
      <button onClick={handleSubmit} disabled={isPending}>
        Update
      </button>
      {error && <p>{error}</p>}
    </div>
  );
}

The async transition will immediately set the isPending state to true, make the async request(s), and switch isPending to false after any transitions. This allows you to keep the current UI responsive and interactive while the data is changing.

Actions automatically manage submitting data for you:

  • Pending state: Actions provide a pending state that starts at the beginning of a request and automatically resets when the final state update is committed.
    Optimistic updates: Actions support the new useOptimistic hook so you can show users instant feedback while the requests are submitting.
  • Error handling: Actions provide error handling so you can display Error Boundaries when a request fails, and revert optimistic updates to their original value automatically.
  • Forms: <form> elements now support passing functions to the action and formAction props. Passing functions to the action props use Actions by default and reset the form automatically after submission.
  • React Canary
    Canaries mark a shift in our React development approach. Unlike the previous method where features were researched and developed privately within Meta, Canaries involved building in public with community collaboration to refine features showcased in the React Labs blog series. This approach ensures that users are informed about upcoming features earlier in the development process. It allows them to witness the finalization stages rather than only encountering the polished product upon Stable release.

Some of the features in the react canary are
React Server Components, Asset Loading, Document Metadata, and Actions

  1. React Server Components
    Server Components are a new type of component in React that render ahead of time, before bundling, in an environment distinct from your client app or SSR server. This distinct environment is the “server” in React Server Components. These components can either run once at build time on your CI server or be executed for each request using a web server.
    A common misunderstanding is that Server Components are denoted by "use server", but there is no directive for Server Components. The "use server" directive is used for Server Actions.

  2. Directives
    "use client" and "use server" are bundler features designed for full-stack React frameworks. They mark the “split points” between the two environments: "use client" instructs the bundler to generate a <script> tag (like Astro Islands), while "use server" tells the bundler to generate a POST endpoint (like tRPC Mutations). Together, they let you write reusable components that compose client-side interactivity with the related server-side logic.

function BlogPost({post}) {
  return (
    <article>
      <h1>{post.title}</h1>
      <title>{post.title}</title>
      <meta name="author" content="Josh" />
      <link rel="author" href="https://twitter.com/joshcstory/" />
      <meta name="keywords" content={post.keywords} />
      <p>
        Eee equals em-see-squared...
      </p>
    </article>
  );
}
  1. Document Metadata:
    Support for rendering <title>, <meta>, and metadata <link> tags anywhere in your component tree has been added. These work the same way in all environments, including fully client-side code, SSR, and RSC. This provides built-in support for features pioneered by libraries like React Helmet.

  2. Actions
    Actions are to manage sending data from the client to the server. You can add action to elements like <form/>, access the status with useFormStatus, handle the result with useFormState, and optimistically update the UI with useOptimistic.

import { useOptimistic } from 'react';

function AppContainer() {
  const [optimisticState, addOptimistic] = useOptimistic(
    state,
    // updateFn
    (currentState, optimisticValue) => {
      // merge and return new state
      // with optimistic value
    }
  );
}

To get started with the React canary

//for npm 
npm install react@canary react-dom@canary
//for yarn
yarn add react@canary react-dom@canary

Creating a dedicated testing environment is preferable to modifying your current production dependencies. This approach enables you to offer feedback without causing disruptions to your live applications.

That is all for now. See you in my next post. Kindly like, share, comment, and follow.

Discover and read more posts from Emmanuel Gbenga
get started
post comments1Reply
Alban Osmani
6 months ago

Wow, this article perfectly captures the excitement around React 19! The introduction of refined concurrent rendering and new state-handling mechanisms indeed mark significant advancements. These features not only enhance performance but also streamline the development process, which is crucial for creating smooth and dynamic user experiences in entertainment apps. I’m particularly excited about how these innovations will enable faster and more responsive features, improving user engagement and satisfaction. Great insights and a comprehensive overview—thanks for sharing this!

Feel free to visit for entertainment app https://apphitv.com/hitv-old-version/