What's new in React 19
Since it was launched by Facebook, now Meta, in 2013, React has changed how we do front-end development with its component-based architecture and declarative style. With the Release Candidate of React 19 available as of April 25, 2024, we find the developer community all abuzz with excitement. Let's dive into what is new in React 19 and improvements that might make it a good idea to upgrade your projects.
What's New in React 19?
React 19 is full of features and improvements to smoothen development. The following is the comprehensive view:
Actions
Actions is a new way of handling data mutation and state changes which at the same time supports async functions in transitions, making pending states, errors, forms, and optimistic updates easier to handle automatically.
Example: Using Actions with useTransition
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>
);
}
New Hooks and APIs
React 19 provides a number of new hooks and APIs to drive state management and side effects. This includes:
-
useActionState: A new hook that covers common cases for Actions.
-
useFormStatus: Access to form status information.
-
useOptimistic: Manage optimistic updates.
-
use: A new API for resources read in render, including the reading of promises and context.
Example: Using useActionState
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>
);
}
Example: Using the new 'use' API
import {use} from 'react';
function Comments({commentsPromise}) {
// `use` will suspend until the promise resolves.
const comments = use(commentsPromise);
return comments.map(comment => <p key={comment.id}>{comment}</p>);
}` ``
function Page({commentsPromise}) {
return (
<Suspense fallback={<div>Loading.</div>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
)
}
React Server Components
React 19 fully supports Server Components and Server Actions. It allows to render some of the components early, before bundling, in an environment that is decoupled from your client application or SSR server.
Other Improvements in React
-
ref as a prop: Function components can now access
ref
as a prop without needingforwardRef
. -
Better hydration error reporting: Human-readable error reports that include diffs for hydration errors.
-
<Context> as a provider: Simplified syntax for context providers.
-
Cleanup functions for refs: Support for returning cleanup functions from ref callbacks.
-
useDeferredValue improvements: Add an
initialValue
option touseDeferredValue
. -
Document Metadata Support: Idera-native support for rendering
<title>
and<meta>
tags in components.Example:
function BlogPost({post}) { return ( <article> <h1>{post.title}</h1> <title>{post.title}</title> <meta name="author" content="Josh Story" /> <link rel="author" href="https://twitter.com/joshcstory/" /> <meta name="keywords" content={post.keywords} /> <p> Eee equals em-see-squared. </p> </article> );
}
7. **Stylesheet Support**: This means native support for supporting stylesheets with precedence.
Example:
```javascript
function ComponentOne() {
return (
<Suspense fallback="loading.">
<link rel="stylesheet" href="foo" precedence="default" />
<link rel="stylesheet" href="bar" precedence="high" />
<article className="foo-class bar-class">
{/* Content */}
</article>
</Suspense>
)
}
-
Async Script Support: It improves the support for rendering async scripts anywhere in the component tree.
-
Resource Preloading: New APIs to preload and prefetch resources.
Example:
import { prefetchDNS, preconnect, preload, preinit } from 'react-dom' function MyComponent() { preinit('https://./path/to/some/script.js', {as: 'script' }) preload('https://./path/to/font.woff', { as: 'font' }) preload('https://./path/to/stylesheet.css', { as: 'style' }) prefetchDNS('https://example.com') preconnect('https://api.example.com')
…… }
10. **Third-party Script Compatibility**: Improved hydration for third-party scripts and browser extensions.
11. **Better Error Reporting**: Improved error handling for new root options for error management.
12. **Custom Elements Support**: Full support for custom elements which pass all tests on Custom Elements Everywhere.
React 19 supports the following strategy for properties that work both on the client and during SSR:
Server Side Rendering: Props with primitive values render as attributes, while non-primitive props are omitted.
Client Side Rendering: Props matching a Custom Element instance property are assigned as properties, otherwise as attributes.
## Conclusion
React 19deojs is full of features and improvements designed to improve performance, usability, and developer experience. A more complete and advanced support for Server Components, better resource loading, changes to error handling, make React 19 a serious upgrade.
Probably some changes may require updates in existing code, but new capabilities and performance improvements of React 19 make it worth upgrading for many projects.
For a list of breaking changes and upgrade instructions, check out the official React 19 Upgrade Guide.
Happy coding with React 19! ????