React 19 is Coming, What’s New?
Published: 2024-03-13 08:43:11

The last time React released a version was on June 14, 2022, with the version number being 18.2.0. In the field of front-end development, such a slow pace of updates for a popular technology is indeed rare. This has led to dissatisfaction among some influential figures in the community, which I mentioned in my previous article. Those interested can click to view: 
[Disagreements in the React Community.](https://weijunext.com/article/react-server-components-discussion)

Against the backdrop of growing dissatisfaction in the community, news of the new version of React has finally arrived.

The React team has also responded to the criticism of not releasing a new official version for so long: the features previously released to the Canary version, due to their interrelated nature, required the React team to invest a lot of time to ensure they could work together before gradually releasing them to the Stable version.

Indeed, although no official version has been released for nearly two years, the Canary version has seen some significant updates, such as the use, useOptimistic hook, and use client, use server directives. These updates have objectively enriched the React ecosystem, especially promoting the rapid development of full-stack frameworks such as Next.js and Remix.

The React team has confirmed that the next version will be a major release, with the version number being 19.0.0.

## Predicting New Features in v19

Now, let’s take an early look at the new features that might be officially released in version 19, based on the latest news from the React team.

**Automatic Memoization**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/peof8ydbdqb846yv5x7j.png)


Do you remember React Forget introduced by Huang Xuan at React Conf 2021?


Now, it’s here.

It’s a compiler that has already been applied in Instagram’s production environment. The React team plans to apply it on more platforms within Meta and will make it open source in the future.

Before using the new compiler, we used **useMemo**, **useCallback**, and memo to manually cache states to reduce unnecessary re-renders. Although this implementation is feasible, the React team believes it’s not the ideal way they envision. They have been looking for a solution that allows React to automatically and only re-render the necessary parts when state changes. After years of effort, the new compiler has now successfully landed.

The new React compiler will be an out-of-the-box feature, representing another paradigm shift for developers. This is the most anticipated feature of v19.

Interestingly, the React team did not mention “React Forget” when introducing the new compiler, which led to a humorous comment from the community: They forget React Forget & forget to mentioned Forget in the Forget section.🤣

**Actions**

React Actions developed as part of the React team’s exploration of solutions for sending data from the client to the server. This feature allows developers to pass a function to DOM elements (such as `<form/>`):

```
<form action={search}>
   <input name="query" />
   <button type="submit">Search</button>
</form>
```

The action function can be synchronous or asynchronous. When using actions, React manages the lifecycle of data submission for the developer. We can access the current status and response of form operations through the **useFormStatus** and **useFormState** hooks.

Actions can be used in scenarios of client-to-server interaction, such as making database changes (adding, deleting, updating data) and implementing forms (such as login forms, registration forms).

In addition to combining with **useFormStatus **and **useFormState**, actions can also be used with **useOptimistic **and use server. Expanding on this in detail would make for a lengthy discussion, but you can follow me for an upcoming article where I will introduce the detailed usage of actions.

**Directives: use client and use server**

The use client and use server directives have been available in the Canary version for a while and are finally joining the Stable version in v19.

Previously, there were frequent complaints in the community about Next.js using these two directives in production, accusing Next.js of damaging the React ecosystem and criticizing the React team for allowing Next.js to use unstable features ahead of time. However, this concern is largely unnecessary because these two directives are designed for full-stack frameworks like Next.js and Remix. Ordinary developers using React to develop applications will hardly need them in the short term.

If you are using React, not a full-stack framework, you only need to understand the purpose of these two directives: use client and use server mark the “split points” between the front-end and server-side environments. use client instructs the packaging tool to generate a `<script>` tag, while use server tells the packaging tool to create a POST endpoint. These directives allow developers to write both client-side and server-side code in the same file.

**useOptimistic for Optimistic Updates**

**useOptimistic** is a new hook likely to be marked as stable in v19. **useOptimistic** allows you to optimistically update the UI during asynchronous operations (such as network requests). It accepts the current state and an update function as parameters, returning a copy of the state that may differ during the asynchronous operation. You need to provide a function that takes the current state and the input of the operation and returns the optimistic state to be used while waiting for the operation.

Here’s how it is defined:

```
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);

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

**Parameters**

**state**: The initial state value and the value returned when no operations are in progress.
**updateFn(currentState, optimisticValue)**: A function that takes the current state and the optimistic value passed to **addOptimistic**, returning the optimistic state result. **updateFn**receives two parameters: **currentState**and **optimisticValue**. The return value will be the merged value of **currentState**and **optimisticValue**.

Return Values

**optimisticState**: The generated optimistic state. When an operation is in progress, it equals the value returned by **updateFn**; when no operation is in progress, it equals state.
**addOptimistic**: This is the dispatch function called during an optimistic update. It accepts one parameter, **optimisticValue**(of any type), and calls **updateFn**with state and **optimisticValue**.

A more detailed example:

```
import { useOptimistic } from 'react';
function AppContainer() {
  const [state, setState] = useState(initialState); // Assume there's an initial state
  const [optimisticState, addOptimistic] = useOptimistic(
    state,
    // updateFn
    (currentState, optimisticValue) => {
      // Merge and return: new state, optimistic value
      return { …currentState, …optimisticValue };
    }
  );
  // Assume there's an asynchronous operation, like submitting a form
  function handleSubmit(data) {
    // Use optimistic update before the actual data submission
    addOptimistic({ data: 'optimistic data' });
    // Then perform the asynchronous operation
    fetch('/api/submit', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
      })
      .then(response => response.json())
      .then(realData => {
        // Update the state with actual data
        setState(prevState => ({ …prevState, data: realData }));
    });
  }
  return (
    // Render UI using optimisticState
    <div>{optimisticState.data}</div>
  );
}
```

useOptimistic renders the anticipated result during the asynchronous operation, and once the operation is completed and the state updated, it renders the real result (whether successful or not).


**Other Updates**
Besides, React team member Andrew Clark also revealed that there would be the following changes in 2024:

🟡 forwardRef → ref is a prop: Simplifying the way references to inner elements or components in a child component are made by treating ref as a regular prop.
🟡 React.lazy → RSC, promise-as-child: Enhanced code splitting and lazy loading capabilities.
🟡 useContext → use(Context): Offering a new way to access Context.
🟡 throw promise → use(promise): Improving the handling of asynchronous data loading.
🟡 `<Context.Provider>` → `<Context>`: Simplifying the use of context providers.

However, the official React website has not provided detailed information on these potential updates yet.

## Conclusion
React has a grand vision. They aim to blur the lines between the front-end and back-end while maintaining their advantage in client-side capabilities and providing infrastructure for the community’s full-stack frameworks. I highly appreciate their approach because breaking down the barriers between the front-end and back-end can help front-end engineers break through their career ceilings.

React 19 will be another milestone version following the introduction of hooks. Andrew Clark said the new version would be released in March or April. Let’s wait and see!