React 19 beta is out! New Hooks & APIs.
React 19 beta has landed, bringing along some unique features to the React ecosystem. We take a look at some of these new Hooks and APIs and how they improve how we build our React applications.
React 19 beta has landed, bringing along some unique updates and features to the React ecosystem. In today’s email, we’ll be taking a look into some of the new Hooks & APIs React 19 brings, shedding light on how some of these changes can improve how we develop our React applications moving forward.
This post marks the first informative issue we’re sending to the “Building Large Scale Apps” newsletter community. In this newsletter, we’ll be sharing content on building and maintaining large-scale web applications, with a focus on front-end engineering and JavaScript technologies.
Some content we share will focus more on exploring code changes and API enhancements (like this article!), while other content will dive into sharing experiences, case studies, or insightful anecdotes from seasoned engineers in the industry working with large-scale web apps.
To get issues like this in your inbox, be sure to subscribe!
React 19
React 19 has made an entrance into the scene on April 25, 2024, with its official beta release. This new version comes packed with a slew of changes including new Hooks & APIs, React Server Components, the removal of some deprecated React APIs, and a lot more. In today’s issue, we'll be primarily focusing on exploring some of the exciting new Hooks & APIs that React 19 introduces.
Keep in mind React 19 is still in beta to primarily target library developers to experiment with and adapt their libraries for the upcoming changes. General app developers are encouraged to upgrade to React 18.3 and await React 19's stable release. For more details and information on upgrading to React 19, the React team has laid out a great React 19 Beta Upgrade Guide that you can check out.
Form submissions and optimistic updates
A large part of how we use web applications today involves interacting with forms for various purposes, from user authentication to data submission to e-commerce transactions, feedback collection, search queries, and much more. As a result, a very common behavior in React component development involves making form submissions of a sort and handling the asynchronous updates of what the form should do when submitted.
A simple example of a form component handling such async updates can look something like the following:
In the above example, the Component
manages a form's state and handles form submission asynchronously. Upon submission, the submitForm()
function submits the form information to a server and returns a response. The component updates its state accordingly, displaying feedback to the user about the submission process.
In React 18, this concept of transitioning the UI from one view to another in a non-urgent manner was given the name of transitions. React 19 now supports using async functions in transitions where the useTransition Hook can also be leveraged to manage the rendering of loading indicators or placeholders during asynchronous data fetching.
Actions
In React 19, the concept of transitions is taken a step further as functions that use async transitions are now referred to as Actions. There now exist a few specialized Hooks to manage Actions like what we’ve seen above and the first we’ll take a look at is the useActionState Hook.
useActionState
The useActionState()
Hook accepts three parameters:
An "action" function, which is executed when the form action is triggered.
An initial state object, that sets the starting state of the form before any user interaction.
[Optional] A permalink that refers to the unique page URL that this form modifies.
And returns three values in a tuple:
The current state of the form.
A function to trigger the form action.
A boolean indicating whether the action is pending.
The action
function passed down as the first argument to the useActionState Hook is triggered when the form submits and returns the form state we expect to transition to when the form submission is either successful or encounters errors. The function receives two parameters — the current state of the form and form data the moment the action was triggered.
Here’s an example of creating an action()
function that calls a hypothetical submitForm()
function that subsequently triggers an API call to submit the form data to a server. When the action is successful, it returns a form state object representing the next state of the form. When the action fails, it returns a form state object reflecting the error state, possibly including error messages or indicators to guide the user in correcting the issue.
With our useActionState()
Hook set-up, we’re then able to use the form state
, dispatch
, and isPending
values in our form template.
<form>
actions
With React 19, <form>
elements now have an action
prop that can receive an action function that will be triggered when a form is submitted. Here is where we’ll pass down the dispatch
function from our useActionState()
Hook.
We can display the state
somewhere in our form template and use the isPending
value to convey to the user when the async action is in flight.
Voila! With these new changes to React, we no longer need to handle pending states, errors, and sequential requests manually when working with async transitions in forms. Instead, these values are accessed directly from the useActionState()
Hook.
Here’s a more detailed Github Gist of the above example that interacts with the publicly available dummyjson API — Github Gist.
useFormStatus
React 19 introduces another new Hook titled useFormStatus that allows nested child components to access information about the form they’re situated in (just like if the form was a context provider).
Though the behavior of accessing parent form information can be done via Context, React 19 introduces the useFormStatus
Hook to make the common case of handling form data within nested components much easier.
useOptimistic
The useOptimistic()
Hook is another new Hook in React 19. It allows us to perform optimistic updates while a background operation, like a network request, completes. This can improve the user experience by providing a faster response to user interactions.
Below is an example of using the useOptimistic()
Hook to manage optimistic updates for a message
state property being passed in as props.
In the above component example, the useOptimistic
Hook is used to manage optimistic updates of the message
state being passed down as a prop.
When the user submits the form by clicking the "Add Message" button, the submitForm()
function is triggered. Before initiating the API request to update the message, the setOptimisticMessage()
function is called with the new message value obtained from the form data. This immediately updates the UI to reflect the optimistic change, providing the user with instant feedback.
When the update finishes or errors, React will automatically switch back to the message
prop value.
The new use API
React 19 introduces a new use API as a versatile way to read values from resources like Promises or context.
For instance, to read context values, we simply pass the context to use()
, and the function traverses the component tree to find the closest context provider.
Unlike the useContext()
Hook to read context, the use()
function can be used within conditionals and loops in our components!
use()
also integrates seamlessly with Suspense
and error boundaries, to read promises (see more in Streaming data from the server to the client of React docs).
React Server Components
React Server Components are a new capability being introduced in React 19 that allows us to create stateless React components that run on the server. These components run ahead of time and before bundling in an environment different from the client application (or server-side-rendered server).
Since React Server Components are able to run on a web server, they can be used to access the data layer without having to interact with an API!
How cool is that! With this, we don’t have to expose an API endpoint or use additional client-side fetching logic to load data directly into our components. All the data handling is done on the server.
Keep in mind that Server Components are run on the server and not the browser. As a result, they’re unable to use traditional React component APIs like useState
. To introduce interactivity to a React Server Component setting, we’ll need to leverage Client Components that complement the Server Components for handling interactivity.
To continue the above blog-post example, this can look something like having the Comment
component being rendered to be a Client component that includes some state and interactivity.
Notice the declaration of “use client” at the top of the component file in the example above. When working with React Server Components, “use client” denotes that the component is a Client Component, which means it can manage state, handle user interactions, and use browser-specific APIs. This directive explicitly tells the React framework and bundler to treat this component differently from Server Components, which are stateless and run on the server.
On the flip-side, React Server Components are the default so we don’t state “use server” at the top of Server Component files. Instead, “use server” should only be used to mark server-side functions that can be called from Client Components. These are called Server Actions.
React Server Components change how we structure our React applications by separating concerns between client and server. The React team believes they will eventually be widely adopted and change the way we build React applications. At this very moment, we’re currently working on a full deep-dive into React Server Components as part of the new chapter “React in 2024” that we’ll be adding to the “Building Large Scale Web Apps” book. We’ll have more to share on this later!
If you’ve purchased the “Building Large Scale Web Apps” book and are greatly enjoying the book, we'd be incredibly grateful if you could leave a positive review! Your feedback helps us reach more developers and continue creating high-quality content like this.
For more details on the new features in React 19 and how you can begin trying out the beta, be sure to check out the React 19 Beta documentation from the official React docs.
See you next week!
Your friends, Addy & Hassan
We hope you enjoyed this read-through on some of the new Hooks and API React 19 is slated to bring. We’ll be sharing more information around this topic in some upcoming emails within the next few weeks.
Enjoyed this issue? Be sure to subscribe to get this newsletter directly in your inbox.