What’s new in React v18.0?

npm install react@18 react-dom@18

1. The Legacy Root API vs. The New Root API

  • Legacy root API: This is the existing API called with ReactDOM.render. This creates a root running in “legacy” mode, which works exactly the same as React 17. Before release, the React team will add a warning to this API indicating that it’s deprecated and to switch to the New Root API.
  • New root API: The new Root API is called with ReactDOM.createRoot. This creates a root running in React 18, which adds all of the improvements of React 18 and allows you to use concurrent features. This will be the root API moving forward.
//React 17import * as ReactDOM from "react-dom"
import App from "App"

// The <App/> component is directly attached to a DOM element with the id of 'app':
ReactDOM.render(<App />, document.getElementById("app"))
//React 18import * as ReactDOM from "react-dom"
import App from "App"
// Create a root by using ReactDOM.createRoot():
const root = ReactDOM.createRoot(document.getElementById("app"))
// Render the main <App/> element to the root:
root.render(<App/>)
import ReactDOM from 'react-dom'
import App from 'App'
//React 17const container = document.getElementById('app');
ReactDOM.hydrate(<App />, container)
//React 18const container = document.getElementById('root');
const root = ReactDOM.createRoot(container, { hydrate: true });
root.render(<App />);

2. Concurrent features

  • startTransition: lets you keep the UI responsive during an expensive state transition.
import { startTransition } from "react"// Urgent update that shows whatever is typed by the user:
setInputValue(inputData);
// Transition updates are marked with startTransition:
startTransition(() => {
// A non-urgent, interruptable update of the search query:
setSearchQuery(inputData);
})
import { useTransition } from "react"
const [isPending, startTransition] = useTransition()
// For example, you can show a loading spinner when it's pending:
{
isPending ? <LoadingSpinner /> : null
}
  • The useDeferredValuehook helps you defer updating some part of the UI by a specified time period while keeping the page responsive. You can also give it an optional timeout. React will try to update the deferred value as soon as it can. If it fails to do so within the given timeout period, it will then force the update, blocking the UI in the process. In other words, the deferred value is updated via a transition update rather than an urgent update, keeping your UI responsive in the process.
import { useDeferredValue } from "react"const deferredValue = useDeferredValue(value, {
timeoutMs: 3000,
})
  • useId : we can use this new hook to create a new identifier in the server and in the client.
function Checkbox() {
const id = useId();
return (
<>
<label htmlFor={id}>Do you follow This Dot on Twitter?</label>
<input id={id} type="checkbox" name="react"/>
</>
);
};

3. Automatic batching

function handleClickEvent() {
// React 17: Re-rendering happens after both of the states are updated
// This is also done in React 18 by default.
setIsLoggedIn(loggedIn => !loggedIn);
setCount(count => count+ 1);
}
// For the following code blocks, React 18 does automatic batching, but React 17 doesn't.
// 1. Promises:
function handleClickEvent() {
fetchData().then(() => {
setIsLoggedIn(loggedIn => !loggedIn)
setCount(count => count+ 1)
})
}
// 2. Asynchronous code:
setInterval(() => {
setIsLoggedIn(loggedIn => !loggedIn)
setCount(count => count+ 1)
}, 3000)
// 3. Native event handlers:
element.addEventListener("click", () => {
setIsLoggedIn(loggedIn => !loggedIn)
setCount(count => count+ 1)
})

4. New Suspense SSR and Selective Hydration

  • Server-side rendering, also known as SSR, is a way of rendering web pages that let you generate HTML from React components directly on the server and share the HTML with users. Users can see a preview of the page through SSR even before the JavaScript bundle presents loads and runs. But sometimes, the JavaScript on the backend takes a long time to get processed, and the time taken is known as Hydrating Time (The process of rendering React components and adding event handlers to the server-side rendered HTML document is referred to as hydration).
  • React 18 will include architectural improvements to the React SSR’s performance. The new update will allow Streaming HTML directly on the server, i.e., the server sends pieces of components as they get rendered using another component known as Suspense, which decides which parts of the application might take longer to load and what shall be rendered directly. Using a selective hydration method, components that are wrapped with Suspense will not block hydration anymore. Every ready component will start hydrating once the browser gets both its content and JavaScript code.

<SuspenseList> </SuspenseList>

import { Suspense, SuspenseList } from "react";<SuspenseList revealOrder="forwards">
<Suspense fallback="Loading first item...">
<FirstItem />
</Suspense>
<Suspense fallback="Loading second item...">
<SecondItem />
</Suspense>
<Suspense fallback="Loading third item...">
<ThirdItem />
</Suspense>
</SuspenseList>

5. Strict mode

6. Components Can Now Render undefined

7. No setState Warning on Unmounted Components

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rahul

Rahul

Full stack developer, Entrepreneur, Founder of zovo