React v19 – React
Warning: Text content did not match. Server: “Server” Client: “Client”
at span
at App
.
Warning: Text content did not match. Server: “Server” Client: “Client”
at span
at App
.
Uncaught Error: Text content does not match server-rendered HTML.
at checkForUnmatchedText
…
We now log a single message with a diff of the mismatch:
– A server/client branch
if (typeof window !== 'undefined').– Variable input such as
Date.now() or Math.random() which changes each time it’s called.– Date formatting in a user’s locale which doesn’t match the server.
– External changing data without sending a snapshot of it along with the HTML.
– Invalid HTML tag nesting.
It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
+ Client
– Server
at throwOnHydrationMismatch
…
as a provider
In React 19, you can render as a provider instead of :
const ThemeContext = createContext('');
function App({children}) {
return (
<ThemeContext value="dark">
{children}
ThemeContext>
);
}
New Context providers can use and we will be publishing a codemod to convert existing providers. In future versions we will deprecate .
Cleanup functions for refs
We now support returning a cleanup function from ref callbacks:
<input
ref={(ref) => {
return () => {
};
}}
/>
When the component unmounts, React will call the cleanup function returned from the ref callback. This works for DOM refs, refs to class components, and useImperativeHandle.
Due to the introduction of ref cleanup functions, returning anything else from a ref callback will now be rejected by TypeScript. The fix is usually to stop using implicit returns, for example:
- <div ref={current => (instance = current)} />
+ <div ref={current => {instance = current}} />
The original code returned the instance of the HTMLDivElement and TypeScript wouldn’t know if this was supposed to be a cleanup function or if you didn’t want to return a cleanup function.
You can codemod this pattern with no-implicit-ref-callback-return.
useDeferredValue initial value
We’ve added an initialValue option to useDeferredValue:
function Search({deferredValue}) {
const value = useDeferredValue(deferredValue, '');
return (
<Results query={value} />
);
}
When initialValue is provided, useDeferredValue will return it as value for the initial render of the component, and schedules a re-render in the background with the deferredValue returned.
For more, see useDeferredValue.
Support for Document Metadata
In HTML, document metadata tags like , , and are reserved for placement in the section of the document. In React, the component that decides what metadata is appropriate for the app may be very far from the place where you render the or React does not render the at all. In the past, these elements would need to be inserted manually in an effect, or by libraries like react-helmet, and required careful handling when server rendering a React application.
In React 19, we’re adding support for rendering document metadata tags in components natively:
function BlogPost({post}) {
return (
<article>
<h1>{post.title}h1>
<title>{post.title}title>
<meta name="author" content="Josh" />
<link rel="author" href=" />
<meta name="keywords" content={post.keywords} />
<p>
Eee equals em-see-squared...
p>
article>
);
}
When React renders this component, it will see the and tags, and automatically hoist them to the section of document. By supporting these metadata tags natively, we’re able to ensure they work with client-only apps, streaming SSR, and Server Components.
For more info, see the docs for , , and .
Support for stylesheets
Stylesheets, both externally linked () and inline (), require careful positioning in the DOM due to style precedence rules. Building a stylesheet capability that allows for composability within components is hard, so users often end up either loading all of their styles far from the components that may depend on them, or they use a style library which encapsulates this complexity.
In React 19, we’re addressing this complexity and providing even deeper integration into Concurrent Rendering on the Client and Streaming Rendering on the Server with built in support for stylesheets. If you tell React the precedence of your stylesheet it will manage the insertion order of the stylesheet in the DOM and ensure that the stylesheet (if external) is loaded before revealing content that depends on those style rules.
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>
)
}
function ComponentTwo() {
return (
<div>
<p>{...}p>
<link rel="stylesheet" href="baz" precedence="default" /> <-- will be inserted between foo & bar
div>
)
}
During Server Side Rendering React will include the stylesheet in the , which ensures that the browser will not paint until it has loaded. If the stylesheet is discovered late after we’ve already started streaming, React will ensure that the stylesheet is inserted into the on the client before revealing the content of a Suspense boundary that depends on that stylesheet.
During Client Side Rendering React will wait for newly rendered stylesheets to load before committing the render. If you render this component from multiple places within your application React will only include the stylesheet once in the document:
function App() {
return <>
<ComponentOne />
...
<ComponentOne /> // won't lead to a duplicate stylesheet link in the DOM
>
}
For users accustomed to loading stylesheets manually this is an opportunity to locate those stylesheets alongside the components that depend on them allowing for better local reasoning and an easier time ensuring you only load the stylesheets that you actually depend on.
Style libraries and style integrations with bundlers can also adopt this new capability so even if you don’t directly render your own stylesheets, you can still benefit as your tools are upgraded to use this feature.
For more details, read the docs for and .
Support for async scripts
In HTML normal scripts () and deferred scripts () load in document order which makes rendering these kinds of scripts deep within your component tree challenging. Async scripts () however will load in arbitrary order.
In React 19 we’ve included better support for async scripts by allowing you to render them anywhere in your component tree, inside the components that actually depend on the script, without having to manage relocating and deduplicating script instances.
function MyComponent() {
return (
<div>
<script async={true} src="..." />
Hello World
div>
)
}
function App() {
<html>
<body>
<MyComponent>
...
<MyComponent> // won't lead to duplicate script in the DOM
body>
html>
}
In all rendering environments, async scripts will be deduplicated so that React will only load and execute the script once even if it is rendered by multiple different components.
In Server Side Rendering, async scripts will be included in the and prioritized behind more critical resources that block paint such as stylesheets, fonts, and image preloads.
For more details, read the docs for .
Support for preloading resources
During initial document load and on client side updates, telling the Browser about resources that it will likely need to load as early as possible can have a dramatic effect on page performance.
React 19 includes a number of new APIs for loading and preloading Browser resources to make it as easy as possible to build great experiences that aren’t held back by inefficient resource loading.
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://...')
preconnect('https://...')
}
<html>
<head>
<link rel="prefetch-dns" href="https://...">
<link rel="preconnect" href="https://...">
<link rel="preload" as="font" href="https://.../path/to/font.woff">
<link rel="preload" as="style" href="https://.../path/to/stylesheet.css">
<script async="" src="https://.../path/to/some/script.js">script>
head>
<body>
...
body>
html>
These APIs can be used to optimize initial page loads by moving discovery of additional resources like fonts out of stylesheet loading. They can also make client updates faster by prefetching a list of resources used by an anticipated navigation and then eagerly preloading those resources on click or even on hover.
For more details see Resource Preloading APIs.
Compatibility with third-party scripts and extensions
We’ve improved hydration to account for third-party scripts and browser extensions.
When hydrating, if an element that renders on the client doesn’t match the element found in the HTML from the server, React will force a client re-render to fix up the content. Previously, if an element was inserted by third-party scripts or browser extensions, it would trigger a mismatch error and client render.
In React 19, unexpected tags in the and will be skipped over, avoiding the mismatch errors. If React needs to re-render the entire document due to an unrelated hydration mismatch, it will leave in place stylesheets inserted by third-party scripts and browser extensions.
Better error reporting
We improved error handling in React 19 to remove duplication and provide options for handling caught and uncaught errors. For example, when there’s an error in render caught by an Error Boundary, previously React would throw the error twice (once for the original error, then again after failing to automatically recover), and then call console.error with info about where the error occurred.
This resulted in three errors for every caught error:
In React 19, we log a single error with all the error information included:
Additionally, we’ve added two new root options to complement onRecoverableError:
onCaughtError: called when React catches an error in an Error Boundary.onUncaughtError: called when an error is thrown and not caught by an Error Boundary.onRecoverableError: called when an error is thrown and automatically recovered.
For more info and examples, see the docs for createRoot and hydrateRoot.
Support for Custom Elements
React 19 adds full support for custom elements and passes all tests on Custom Elements Everywhere.
In past versions, using Custom Elements in React has been difficult because React treated unrecognized props as attributes rather than properties. In React 19, we’ve added support for properties that works on the client and during SSR with the following strategy:
- Server Side Rendering: props passed to a custom element will render as attributes if their type is a primitive value like
string,number, or the value istrue. Props with non-primitive types likeobject,symbol,function, or valuefalsewill be omitted. - Client Side Rendering: props that match a property on the Custom Element instance will be assigned as properties, otherwise they will be assigned as attributes.
Thanks to Joey Arhar for driving the design and implementation of Custom Element support in React.
How to upgrade
See the React 19 Upgrade Guide for step-by-step instructions and a full list of breaking and notable changes.
Note: this post was originally published 04/25/2024 and has been updated to 12/05/2024 with the stable release.