Reader small image

You're reading from  React 18 Design Patterns and Best Practices - Fourth Edition

Product typeBook
Published inJul 2023
Reading LevelExpert
PublisherPackt
ISBN-139781803233109
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Carlos Santana Roldán
Carlos Santana Roldán
author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán

Right arrow

React 18 New Features

React 18, the latest version of the popular JavaScript library for building user interfaces, introduces a host of new features and enhancements that aim to improve performance and enhance the developer experience. As a part of the ever-evolving React ecosystem, it is crucial to stay up to date with these advancements. In this chapter, we will provide a succinct overview of the most notable additions in React 18, followed by a brief explanation of the latest features in Node.js 19.

The new features in React 18 include:

  • Automatic Batching of State Updates: React 18 automatically batches multiple state updates into a single update, which results in improved performance and smoother animations. This automatic batching eliminates the need for manual batching.
  • Concurrent Rendering: This feature enables React to prioritize the rendering of certain components, leading to faster load times, smoother animations, and better user experiences.
  • Suspense...

React 18 New Features

React 18, the latest version of the popular JavaScript library for building user interfaces, introduces a host of new features and enhancements that aim to improve performance and enhance the developer experience. As a part of the ever-evolving React ecosystem, it is crucial to stay up to date with these advancements. In this chapter, we will provide a succinct overview of the most notable additions in React 18, followed by a brief explanation of the latest features in Node.js 19.

The new features in React 18 include:

  • Automatic Batching of State Updates: React 18 automatically batches multiple state updates into a single update, which results in improved performance and smoother animations. This automatic batching eliminates the need for manual batching.
  • Concurrent Rendering: This feature enables React to prioritize the rendering of certain components, leading to faster load times, smoother animations, and better user experiences.
  • Suspense...

Concurrent mode

React concurrent mode is a set of new features in React 18 that enable faster and more responsive user interfaces by allowing React to work on multiple tasks simultaneously.

In traditional React, the rendering process is synchronous, which means that React updates the user interface in a single pass. This can sometimes lead to performance issues, especially when rendering large, complex applications or handling real-time updates.

Concurrent mode allows React to split the rendering process into smaller units of work that can be executed independently and in parallel. This means that React can prioritize certain tasks, such as updating the user interface, while still allowing other tasks to run in the background, such as handling user input or fetching data.

Here are some of the key features of React concurrent mode:

  • Time slicing: Time slicing is a technique that allows React to break up large chunks of work into smaller pieces and prioritize...

Automatic batching

Automatic batching is a new feature in React 18 that improves the performance of updates by automatically batching multiple updates into a single render pass. In traditional React, updates to the user interface are typically processed synchronously, which means that each update triggers a new render pass.

This can be inefficient, especially when multiple updates occur in rapid succession. Automatic batching solves this problem by grouping multiple updates together and processing them in a single render pass.

Here’s an example to illustrate how automatic batching works:

function MyComponent() {
  const [count, setCount] = useState(0)
  function handleClick() {
    setCount(count + 1)
    setCount(count + 1)
    setCount(count + 1)
  }
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  )
}

In this example, we have a MyComponent component that...

Transitions

React 18 introduces a new feature called transitions that allows developers to create smooth, declarative animations and transitions in their applications.

Transitions build on the existing capabilities of React’s declarative programming model to provide a simple and intuitive way to animate elements and components.

Here’s a simple example to illustrate how transitions work:

import { useState } from 'react'
import { Transition } from 'react-transition-group'
function MyComponent() {
  const [show, setShow] = useState(false)
  function handleClick() {
    setShow(!show)
  }
  return (
    <div>
      <button onClick={handleClick}>
        {show ? 'Hide' : 'Show'}
      </button>
      <Transition in={show} timeout={300}>
        {(state) => (
          <div
            style={{
              transition: 'opacity 300ms ease-out',
              opacity: state === &apos...

Suspense on the server

React 18 introduces some improvements to server-side rendering (SSR) with Suspense that allow developers to create more efficient and scalable server-rendered applications.

Before React 18, Suspense was primarily used in client-side rendering to manage asynchronous data loading and code splitting. However, with React 18, Suspense can also be used on the server to optimize the rendering of server-rendered components.

Here’s a high-level overview of how Suspense works on the server:

  • During the initial render of a server-rendered component, any Suspense boundaries are registered, and their fallback content is rendered instead of the main content.
  • When data loading or code splitting is required, the server can return a “placeholder” HTML response that contains the fallback content for the Suspense boundaries.
  • Once the asynchronous data or code has loaded, the client can hydrate the Suspense boundaries with the...

New APIs

React 18 has introduced a variety of new APIs that are focused on enhancing the user interface, improving application performance, and providing a better developer experience. Notably, significant additions include createRoot, hydrateRoot, and renderToPipeableStream.

createRoot

React 18 introduces a new API called createRoot, which provides a simpler and more explicit way to render React components into the DOM.

Traditionally, when rendering a React application into the DOM, you would use the ReactDOM.render method to specify the root element and the React component to render into it. For example:

import React from 'react'
import ReactDOM from 'react-dom'
const App = () => {
  return <div>Hello, world!</div>
}
ReactDOM.render(<App />, document.getElementById('root'))

With createRoot, you can create a root element that can be used to render multiple components, instead of specifying the root element for...

New Hooks

In React 18, a set of innovative hooks has been introduced, which provide enhanced techniques for managing IDs, transitions, and optimizing performance. These hooks include useId, useTransition, useDeferredValue, and useInsertionEffect.

useId

useId is a new built-in hook in React 18 that can be used to generate a unique ID. This can be useful in scenarios where you need to generate unique identifiers for elements in a React component, for example, when building forms.

Here’s an example of how you can use useId to generate a unique ID:

import { useId } from 'react'
const MyComponent = () => {
  const id = useId()
  return <div id={id}>Hello, world!</div>
}

In this example, we use the useId hook to generate a unique ID, which we then use as the id attribute of a <div> element.

useId generates a unique ID that is guaranteed to be different on each render. It takes an optional parameter that can be used to specify...

Strict mode

React 18 introduces a new feature called Strict Mode, which allows you to opt in to a stricter set of checks and warnings for your React application. The goal of Strict Mode is to catch potential problems early in development and to encourage best practices that make your code more performant and easier to debug.

Here’s an example of how to use Strict Mode:

import React from 'react'
function MyComponent() {
  return (
    <React.StrictMode>
      <div>
        <h1>Hello, world!</h1>
        <p>This is my React component.</p>
      </div>
    </React.StrictMode>
  )
}

In this example, we wrap our component tree with the React.StrictMode component. This enables several additional checks and warnings during development, such as detecting unsafe lifecycle methods, identifying potential side effects, and highlighting potential performance issues.

Strict Mode does not affect the behavior of your...

Node.js latest features

There are some relevant new features in the latest versions of Node (18 and 19); let’s see what is new in those versions.

Experimental Fetch API

Node.js 18 (also in version 19) includes an experimental global Fetch API that is now available by default. The API’s implementation is inspired by node-fetch, which is originally based on undici-fetch and comes from undici. The API’s developers aim to make it as close to the specification as possible, but some features require a browser environment and are thus omitted.

Here is an example that hits the Pokémon API:

const getPokemons = async () => {
  const response = await fetch('https://pokeapi.co/api/v2/pokemon')
  if (response.ok) {
    const pokemons = await response.json()
    console.log(pokemons)
  } else {
    console.error(`${response.status} ${response.statusText}`)
  }
}
getPokemons()

This addition to Node.js 18 (also included in version 19) makes...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React 18 Design Patterns and Best Practices - Fourth Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781803233109
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Carlos Santana Roldán

Carlos Santana Roldán is a senior web developer with more than 15 years of experience. Currently, he is working as a Principal Engineer at APM Music. He is the founder of JS Education, where he teaches people web technologies such as React, Node.js, JavaScript, and TypeScript.
Read more about Carlos Santana Roldán