Signup/Sign In
LAST UPDATED: MAY 21, 2024

React 19 New Features

    After almost 2 long years, the React team has decided to launch the React 19 version. The React 19 comes packed with new features to improve the performance of the applications developed using ReactJS and reduce the development time for building complex and scalable applications. The ReactJS team is still promoting using some frameworks like NextJS, Relay, Remix, etc. for developing applications with ReactJS, but you can code robust, fast, and scalable applications with just ReactJS too (without any framework).

    In this article, I will share with you the new features that have been added to the new React 19 version. The React 19 new features include a ReactJS compiler, Server side rendering, support for metadata in React components for improving the SEO of web applications, better compatibility with web components, enhanced hooks, actions, etc. to take the application development with ReactJS to the next level.

    react 19 new features

    So without wasting any more time, let's talk about all these new hot features of React 19 in detail.

    React 19 New features

    If you wish to dive deep into the new features along with code examples, you should check out the release page on React.dev blog.

    Want to learn ReactJS, check out our YouTube video series on ReactJS:

    Learn ReactJS

    1. React Compiler

    Yes, React now comes with a compiler that can convert all your React code into regular JavaScript to improve the performance of your application. The prime responsibility of the React compiler is to make sure minimum re-renders are done and minimal components are affected by the re-rendering to ensure a fast, and responsive application.

    The React compiler is now open source and you can find it here: React compiler. The React compiler is built using Rust and you can try it on the online playground available on the React website.

    react compiler

    The next point covers the main reason why the React compiler is being used and how it is improving your application's performance.

    2. Automatic Memoization

    React works on the principle of application state change triggering the UI re-render. You only have to make sure that the application state gets the correct value, and ReactJS will make sure the user interface is re-rendered to keep the UI updated as per the application state. This sounds good, right? However, too many changes to the application state will force the components to re-render again and again, slowing down the application.

    To avoid this, we use memoization. Memoization is a technique to store the output or results of expensive computation tasks, and reuse them for the same inputs, rather than doing the computation again. Now with the new React compiler, you don't have to do this yourself because memoization is automatically done by the React compiler for you.

    So you don't have to use the useMemo, useCallback or memo anymore.

    When the React compiler optimizes any component, you will see a Memo badge added in front of it in the React Devtools (v5.0+), as shown in the screenshot below.

    react compiler developer tool

    3. Server Components

    After months of anticipation, the Server components are part of React 19. Server components, as the name suggests are processed on the server, and the final HTML code is sent to the browser. Traditionally, programming languages like PHP worked like this. Then JavaScript popularized the Client-side UI component creation, but for complex applications, doing a lot of work on the client side leads to slow loading and poor user experience, which is an SEO pitfall.

    Hence, to make the UI load faster, and to improve SEO, React 19 will support Server components. NextJS already supports Server-side rendering, because Server components were available as experimental API from React, and the NextJS team implemented it into their framework.

    The user interface of an application should always be a mix of both Client component and Server components. Server components are good with fetching data, improving SEO for static pages, etc. On the other hand, pages that require client interaction should be client components. Parts of application that are affected by the state, should also be client components.

    4. Actions

    When you build a ReactJS application, one of the most used UI elements is a Form. A form is required to make your application interactive, where the user can provide some input and you can process it. Having a form on a webpage requires data management and user interaction management, and the most common flow is:

    1. Handle form data submission

    2. Track the status of Form

    3. Error handling.

    For example, here is a simple code used for form handling in React,

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

    In the code above, you have to handle data, pending state, and error. This is standard practice, so the ReactJS team decided to simplify this by introducing a few new hooks as part of Actions.

    Following new hooks are introduced in React 19:

    1. useTransition to handle the transition phase of the form - pending, completed, etc.

    2. useOptimistic to manage optimistic updates.

    3. useActionState to wrap the complete handling of the Form that we shared in the code above into a boilerplate code.

    4. useFormStatus to create components with form status awareness, for example, a form submit button can use the form status to disable and enable itself.

    With Actions, you can now take the form handling to the server side, just like we used to do in the good old days using the form tag's action attribute. So let's see how the code will change with useActionState hook, which is the most comprehensive in terms of form handling in React 19.

    function ChangeName({ name, setName }) {
    
      const [error, submitAction, isPending] = useActionState(
        async (previousState, formData) => {
          const error = await updateName(formData.get("name"));
          if (error) {
            return error;
          }
          redirect("/path");
          return null;
        },
        null,
      );
    
      return (
        <form action={submitAction}>
          <input type="text" name="name" />
          <button type="submit" disabled={isPending}>Update</button>
          {error && <p>{error}</p>}
        </form>
      );
    
    }

    As you can see in the code above, the entire form handling is wrapped by the useActionState hook. And we have used the action attribute of the <form> in JSX code.

    You can learn more about React actions on React 19 release notes.

    5. Asset Loading

    The Asset loading has been improved in React 19. The images and static resources are now loaded in the background which will have a significant improvement in the loading speed of components.

    React 19 has introduced many APIs for preloading browser resources. Here is a basic example,

    import { prefetchDNS, preconnect, preload, preinit } from 'react-dom'
    
    function MyComponent() {
        preinit('https://.../path/to/some/script.js', {as: 'script' }) // loads and executes this script eagerly
        preload('https://.../path/to/font.woff', { as: 'font' }) // preloads this font
        preload('https://.../path/to/stylesheet.css', { as: 'style' }) // preloads this stylesheet
        prefetchDNS('https://...') // when you may not actually request anything from this host
        preconnect('https://...') // when you will request something but aren't sure what
    }

    6. Support for Document Metadata

    One very important requirement for SEO of webpages is that the webpage should have proper document metadata like title, link, and description. Earlier, in React, there was no direct way to include this meta information on webpages, and you had to use some 3rd party package like react-helmet. But with React 19, you can now include this information inside your component directly.

    For example,

    function Article({post}) {
      return (
        <article>
          <h1>{post.title}</h1>
          <title>{post.title}</title>
          <meta name="author" content="Abhishek" />
          <link rel="author" href="https://www.studytonight.com/" />
          <meta name="keywords" content={post.keywords} />
          <meta name="description" content={post.description} />
          <p>
              Welcome to Studytonight...
          </p>
        </article>
      );
    }

    When ReactJS will render the component in the code above, it will see the <title>, <link>, and <meta> tags and will hoist them to the <head> section of the document.

    7. Support for Stylesheets

    React 19 has improved the handling of Stylesheets included directly inside the component JSX, either to link an external CSS file or to specify internal CSS code using the <style> tag. React 19 has extended this enhanced support for both client components and server components.

    You can also specify precedence rules while linking your CSS files. Let's see an example,

    function ComponentOne() {
      return (
        <Suspense fallback="loading...">
          <link rel="stylesheet" href="foo" precedence="default" />
          <link rel="stylesheet" href="bar" precedence="high" />
          <article class="foo-class bar-class">
            {...}
          </article>
        </Suspense>
      )
    }

    You can read about it in detail on the React 19 updates blog.

    8. New API - use

    If you make a API request using fetch, then you can handle Promise in JavaScript either by using then() or using async/await. And once the promise is resolved you can load the data in any component.

    Now, you can use the React 19 use API to handle promises during rendering. The use API is used to read resources in general, using it for Promise is just a use case.

    For example,

    function Comments({commentsPromise}) {
    
      // `use` will suspend until the promise resolves.
      const comments = use(commentsPromise);
    
      return comments.map(comment => <div key={comment.id}>{comment}</div>);
    }
    
    function Page({commentsPromise}) {
    
      // When `use` suspends in Comments,
      // this Suspense boundary will be shown.
    
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <Comments commentsPromise={commentsPromise} />
        </Suspense>
      )
    }

    The suspense boundary will also be invoked until the Promise is resolved.

    9. More React 19 New features

    1. With React 19, if you are using context API, then you can directly use the <Context> as a provider instead of <Context.Provider>.

    2. Improved Error handling and error reporting.

    3. ref can now pe passed as a prop to function components.

    Conclusion

    If you want to try the new React 19 new features, you can upgrade your project's React version by following the React version upgrade guide.

    Finally, with React 19, React is working on the basic problems that developers face, which is a step towards becoming a core library to provide a better platform for future frameworks.

    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS