Beliebte Suchanfragen
|
//

React is dead, long live React - React 19 is here

19.7.2024 | 6 minutes of reading time

The world of frontend development has changed once again, and this time React 19 is leading the way. This version brings a variety of new features and improvements, but the most exciting innovation is the brand new compiler, which already requires React 19. In this article, we shall take a detailed look at the changes and delve into the features and benefits of this new compiler. Additionally, there will be a brief overview of the other new additions. However, before we dive in too deep, it should be noted that the new version is still labeled as a Release Candidate. Therefore, all new features should be used with caution.

What exactly is new in React 19?

Introduction of a New Compiler

A key element of the new version is the new compiler that comes with React 19. It has been developed to make the compiled code more efficient, thus optimizing performance. This means that developers will need to worry less about performance optimizations in the future. The React Compiler is the core of the new version and brings many features with it. Firstly, it is available as an open-source project. Secondly, it works as a build-time-only tool and does not require runtime support. Additionally, a Rust version is currently in development, which is expected to further improve performance [1]. To facilitate working with the compiler, there is also an associated ESLint plugin available[2].

The initial release of the React Compiler focuses mainly on improving update performance (re-rendering existing components and memoization of hooks), which is especially beneficial for complex applications. Previously, all types of memoizations were achieved through the use of hooks like useMemo, useCallback, and React.memo. With the help of the compiler, these parts of the code are now fully automated. In concrete terms, whatever does not need to be recalculated, won’t be. [2]

React 18 without a compiler

const Component = () => {
  const [count, setCount] = useState(0);
  const calculation = useMemo(() => expensiveCalculation(count), [count]);

  return (
    <div>
 Calculation: {calculation}
      …
    </div>
  );
};

React 19 with a compiler

const Component = () => {
  const [count, setCount] = useState(0);
  // memoization without useMemo
  const calculation = expensiveCalculation(count)

  return (
    <div>
 Calculation: {calculation}
      …
    </div>
  );
};

The same applies to re-rendering components. The following example shows a component for displaying ToDos and a component for adding more ToDos. Without any memoization, the component and all its child components will be re-rendered whenever the list of ToDos changes. With the help of the React Compiler and its associated memoization, it is automatically recognized that the component for adding ToDos (AddNewTodoComponent) is independent of the displayed ToDos and therefore does not need to be re-rendered.

const TodoList = () => {
  const todos = useTodos();
  return (
    <div>
      <span>{todos.length} todos</span>
      {todos.map((todo) => (
        <TodoEntry key={todo.id} todo={todo} />
      ))}
      <AddNewTodoComponent />
    </div>
  );
}

Conclusion: The new React Compiler eliminates the need for useMemo and useCallback, leading to a more efficient and streamlined codebase.

Server Components

Previously, React components were only rendered on the client side. With Next.js, it has been possible to build applications with Server Components for some time. These are components that are rendered only on the server. With React 19, these are now fully integrated. When using them, it is important to distinguish between Server Components with and without a server. Without a server means that Server Side Rendering is done at build time, allowing static content (e.g., from various files) to be loaded. In contrast, Server Components using a web server are re-rendered with each request [4]. Since the execution takes place on the server, Server Actions can be utilized, and the components do not need to call an additional API. This allows, for example, direct database queries to be performed [3].

import db from './database';
export Todo = async ({id}) => {
  const todo = await db.todos.get(id);
  return (
    <div>
      <Author id={todo.authorId} />
      <p>{todo}</p>
    </div>
  );
}

Benefits of Server Components

  • SEO: Better visibility in search engines since the content is rendered server-side.
  • Performance: Faster initial page load and overall better performance due to server-side execution.
  • Server Side Execution: Better handling of API calls and other server-side tasks.
  • Build-Time Rendering: Components can be rendered at build time and then delivered as static content.

Server Actions

Alongside Server Components, React 19 also introduces Server Actions. This allows asynchronous functions to be executed by the server. By simply annotating a function with ‘use server’, it can be defined as a server-side action. When such a function is called, React sends a request to the server where the function is then executed [5]. A Server Action might look like this:

"use server";

export createTodoAction = async () => {
  await db.todos.create();
}

This Server Action can be used in both Server Components and Client Components (annotated with “use client”). This means that even if an action is triggered on the client side, it can still be executed server-side [5].

Example:

“use client”
import {createTodoAction} from './actions';

const Overview = () => {
  …
  <button onClick={createTodoAction} />
  …
}

New Hooks and Other Features

React 19 brings a variety of new hooks and features that simplify and optimize development.

Actions

A common task in React apps is performing data mutations and subsequently updating the state. Functions that use such asynchronous transitions are called "Actions". Previously, developers had to manually handle pending states, errors, and optimistic updates, often using useState. With React 19, this is simplified through the introduction of Actions. This can be achieved using useTransition as shown below: [3]

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");
   })
 };

use( ) - The New API for Promises and Contexts

The use hook provides a new interface, allowing access to resources during rendering, which reduces the need for useEffect and useState. Resources in this context can refer to Promises or Contexts. [1]

import { use } from 'react';

const NewsComponent = ({ newsPromise }) => {
  const news = use(newsPromise);
  const theme = use(ThemeContext);
  // ...

Additional Features and Hooks

Ref as Prop

In the future, there will be no need to use forwardRef to pass a ref. Ref will become a default prop for components [3].

useOptimistic

The useOptimistic hook allows for temporary updates with optimistic values. This is particularly useful for providing immediate feedback to users while the actual data is still being processed [3].

useFormStatus

The useFormStatus hook can read the state of a form, enabling better handling of form states and validations in child components [3].

Besides the features mentioned here, there are other small enhancements that might be interesting for some. For more details, I would directly refer to the Release Notes of React 19.

Conclusion

React 19 marks a significant advancement in frontend development. The new compiler not only brings with it a dramatically improved performance but also offers a variety of new possibilities and optimizations that make developers' lives easier. With the new tools and improvements, developing React applications will become much more efficient and powerful than before.

Sources

[1] React Compiler Development Guide (Accessed on: 12.07.2024)

[2] React Compiler (Accessed on: 28.06.2024)

[3] React 19 RC (Accessed on: 28.06.2024)

[4] React Server Components (Accessed on: 12.07.2024)

[5] Server Actions (Accessed on: 28.06.2024)

|

share post

Likes

10

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.