Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React 16 Essentials - Second Edition
React 16 Essentials - Second Edition

React 16 Essentials: A fast-paced, hands-on guide to designing and building scalable and maintainable web apps with React 16, Second Edition

By Christopher Pitt , Artemij Fedosejev , Adam Boduch
$25.99 $17.99
Book Nov 2017 240 pages 2nd Edition
eBook
$25.99 $17.99
Print
$32.99
Subscription
$15.99 Monthly
eBook
$25.99 $17.99
Print
$32.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Nov 30, 2017
Length 240 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781787126046
Vendor :
Facebook
Category :
Table of content icon View table of contents Preview book icon Preview Book

React 16 Essentials - Second Edition

Chapter 1. What's New in React 16

The release of React 16 includes enough important changes to devote a chapter to them. This particular release took a comparatively long time to deliver. This is because the reconciliation internals—the part of React that figures out how to efficiently render component changes—was rewritten from the ground up. Compatibility was another factor: this rewrite has no major breaking API changes.

In this chapter, you'll learn about the major changes introduced in React 16:

  • The major changes made to the reconciliation internals, and what they mean for React projects, going forward

  • Confining errors to the sections of your application by setting error boundaries

  • Creating components that render more than one element and components that render strings

  • Rendering to portals

Rethinking rendering


You do not need a deep understanding of how the reconciliation internals of React work. This would defeat the purpose of React and how it encapsulates all of this work for us. However, understanding the motivation for the major internal changes that have happened in React 16 and how they work at a higher level will help you think about how to best design your components today and for the future React applications.

The status quo

React has established itself as one of the standards when it comes to choosing a library to help build user interfaces. The two key factors for this are its simplicity and its performance. React is simple because it has a small API surface that's easy to pick up and experiment with. React is performant because it minimizes the number of DOM operations it has to invoke by reconciling changes in a render tree.

There's an interplay between these two factors that has contributed to React's skyrocketing popularity. The good performance provided by React wouldn't be valuable if the API were difficult to use. The overarching value of React is that it's simple to use and performs well out of the box.

With the widespread adoption of React came the realization that its internal reconciliation mechanics could be improved. For example, some React applications update the component state faster than rendering can complete. Consider another example: changes to part of the render tree that aren't visible on the screen should have a lower priority than elements that the user can see. Issues like these are enough to degrade the user experience so that it doesn't feel as fluid as it could be.

How do you address these issues without disrupting the API and render tree reconciliation that work so well?

Running to completion

JavaScript is single-threaded and run-to-completion. This means that by default, any JavaScript code that you run will block any other browser tasks from running, such as painting the screen. This is why it's especially important that JavaScript code be fast. However, in some cases, even the performance of the React reconciliation code isn't enough to mask bottlenecks from the user. When presented with a new tree, React has no choice but to block the DOM updates and event listeners while it computes the new render tree.

One possible solution is to break the reconciliation work into smaller chunks, and arrange them in such a way that prevents the JavaScript run-to-completion thread from blocking important DOM updates. This would mean that the reconciler wouldn't have to render a complete tree, and then have to do it all over again because an event took place while the first render was taking place.

Let's look at a visual example of this problem:

This figure demonstrates that any time state changes in a React component, nothing else can happen until rendering has completed. As you can see, reconciling entire trees can get expensive as the state changes pile up, and, all the while, the DOM is blocked from doing anything.

Reconciling the render tree is in lock-step with the run-to-completion semantics of JavaScript. In other words, React cannot pause what it's doing to let the DOM update. Let's now look at how React 16 is trying to change the preceding figure:

This version of the React render/reconciliation process looks similar to the previous version. In fact, nothing about the component on the left has changed—this is reflective of the unchanging API in React 16. There are some subtle but important differences though.

Let's start by looking at the reconciler. Instead of building a new render tree every time the component changes state, it renders a partial tree. Putting it another way, it performs a chunk of work that results in the creation of part of a render tree. The reason it doesn't complete the entire tree is so that the reconciliation process can pause and allow any DOM updates to run—you can see the difference in the DOM on the right-hand side of the image.

When the reconciler resumes building the render tree, it first checks to see if new state changes have taken place since it paused. If so, it takes the partially completed render tree and reuses what it can, based on the new state changes. Then, it keeps going until the next pause. Eventually, reconciliation completes. During reconciliation, the DOM has been given a chance to respond to events and to render any outstanding changes. Prior to React 16, this wasn't possible—you would have to wait until the entire tree was rendered before anything in the DOM could happen.

What are fibers?

In order to separate the job of rendering components into smaller units of work, React has created an abstraction called a fiber. A fiber represents a unit of rendering work that can be paused and resumed. It has other low-level properties such as priority and where the output of the fiber should be returned to when completed.

The code name of React 16 during development was React Fiber, because of this fundamental abstraction that enables scheduling pieces of the overall rendering work to provide a better user experience. React 16 marks the initial release of this new reconciliation architecture, but it's not done yet. For example, everything is still synchronous.

Async and the road ahead

React 16 lays the groundwork for the ultimate goal of asynchronous rendering in the next major release. The main reason that this functionality isn't included in React 16 is because the team wanted to get the fundamental reconciliation changes out into the wild. There are a few other new features that needed to be released too, which we'll go over in the following sections.

Once asynchronous rendering capabilities are introduced into React, you shouldn't have to modify any code. Instead, you might notice improved performance in certain areas of your application that would benefit from prioritized and scheduled rendering.

Better component error handling

React 16 introduces better error-handling capabilities for components. The concept is called an error boundary, and it's implemented as a lifecycle method that is called when any child components throw an exception. The parent class that implements componentDidCatch() is the error boundary. You could have different boundaries throughout your application, depending on how your features are organized.

The motivation for this functionality is to give the application an opportunity to recover from certain errors. Prior to React 16, if a component threw an error, the entire app would stop. This might not be ideal, especially if an issue with a minor component stops critical components from working.

Let's create an App component with an error boundary:

class App extends Component {
  state = {}

  componentDidCatch(err) {
    this.setState({ err: err.message });
  }

  render() {
    return (<p><MyError err={this.state.err}/></p>);
  }
}

The App component does nothing but render MyError—a component that intentionally throws an error. When this happens, the componentDidCatch() method is called with the error as an argument. You can then use this value to change the state of the component. In this example, it sets the error message in the err state. Then, App will attempt to re-render.

As you can see, this.state.err is passed to MyError as a property. During the first render, this value is undefined. When App catches the error thrown by MyError, the error is passed back to the component. Let's look at MyError now:

const MyError = (props) => {
  if (props.err) {
    return <b style={{color: 'red'}}>{props.err}</b>;
  }

  throw new Error('epic fail');
};

This component throws an error with the message 'epic fail'. When App catches this error, it renders MyError with an err prop. When this happens, it simply renders the error string in red. This just happens to be the strategy I've chosen for this app; always check for an error state before invoking the errant behavior again. In MyError, the application as a whole is recovered by not executing throw new Error('epic fail') for a second time.

With componentDidCatch(), you're free; set any strategy you like for error recovery. Usually, you can't recover a specific component that fails.

Rendering multiple elements and strings

Since React was first released, the rule was that components could only render one element. This has changed in two important ways in React 16. First, you can now return a collection of elements from your component. This simplifies cases where rendering sibling elements would drastically simplify things. Second, you can now render plain text content.

Both of these changes result in fewer elements on the page. By allowing sibling elements to be rendered by components, you don't have to wrap them with an element for the sake of returning a single element. By rendering strings, you can render test content as the child or another component, without having to wrap it in an element.

Here's what rendering multiple elements looks like:

const Multi = () => [
  'first sibling',
  'second sibling'
].map((v, i) => <p key={i}>{v}</p>);

Note that you have to provide a key property for elements in a collection. Now let's add an element that returns a string value:

const Label = () => 'Name:';

const MultiWithString = () => [
  'first sibling',
  'second sibling'
].map((v, i) => <p key={i}><Label/> {v}</p>);

The Label component simply returns a string as its rendered content. The p element renders Label as a child, adjacent to the {v} value. When components can return strings, you have more options for composing the elements that make up your UI.

Rendering to portals

The final new feature of React 16 that I want to introduce is the notion of portals. Normally, the rendered output of a component is placed where the JSX element is located within the tree. However, there are times when we have greater control over where the rendered output of our components ends up. For example, what if you wanted to render a component outside of the root React element?

Portals allow components to specify their container element at render time. Imagine that you want to display notifications in your application. Several components at different locations on the screen need the ability to render notifications at one specific spot on the screen. Let's take a look at how you can target elements using portals:

import React, { Component } from 'react';
import { createPortal } from 'react-dom';
class MyPortal extends Component {
  constructor(...args) {
    super(...args);
    this.el = document.createElement('strong');
  }

  componentWillMount() {
    document.body.appendChild(this.el);
  }

  componentWillUnmount() {
    document.body.removeChild(this.el);
  }

  render() {
    return createPortal(
      this.props.children,
      this.el
    );
  }
};

In the constructor of this component, the target element is created and stored in the el property. Then, in componentWillMount(), the element is appended to the document body. You don't actually need to create the target element in your component—you can use an existing element instead. The componentWillUnmount() method removes this element.

In the render() method, the createPortal() function is used to create the portal. It takes two arguments—the content to render and the target DOM element. In this case, it's passing its child properties. Let's take a look at how MyPortal is used:

class App extends Component {
  render() {
    return (
      <div>
        <p>Main content</p>
        <MyPortal>Bro, you just notified me!</MyPortal>
      </div>
    );
  }
}

The end result is that the text that's passed to MyPortal is rendered as a strong element outside of the root React element. Before portals, you would have to resort to some kind of imperative workaround in order for something like this to work. Now, we can just render the notification in the same context that it's needed in—it just happens to be inserted somewhere else in the DOM in order to display correctly.

Summary


The goal of this chapter was to introduce you to the substantial changes in React 16. Remarkably, there are almost no compatibility issues with the prior React release. This is because most of the changes were internal and didn't require changes in the API. A couple of new features were added as well.

The headline of React 16 is its new reconciliation internals. Rather than trying to reconcile everything any time a component changes state, the reconciliation work is now broken into smaller units. These units can be prioritized, scheduled, paused, and resumed. In the near future, React will take full advantage of this new architecture and start rendering units of work asynchronously.

You also learned how to use the new error boundary functionality in React components. Using error boundaries allows you to recover from component errors without taking down the entire application. Then, you learned that React components can now return collections of components. This is just like when you render a collection of components. Now you can do this directly from components. Finally, you learned how to render components to nonstandard locations using portals.

In the next chapter, you'll learn how to build reactive components.

Left arrow icon Right arrow icon

Key benefits

  • Hands-on examples and tutorials for the latest React 16 release
  • Assess the impact of React Fiber for your future web development
  • Build maintainable and high performance React 16 web applications

Description

React 16 Essentials, Second Edition, fully updated for React 16, takes you on a fast-paced journey through building your own maintainable React 16 applications. React experts Artemij Fedosejev and Adam Boduch give you all the essentials you need to know and start working with React 16, in this new edition of the best-selling React.js Essentials title. You'll find the latest React 16 code updates, assessment of React Fiber, new coverage of Redux, and how to work as a modern React developer. The authors offer you their current assessment of React Fiber, and you'll soon be exploring React 16 hands on, creating your own single and multiple user interface elements with React 16. You'll then see how to create stateless and stateful components and make them reactive. You'll also learn to interact between your components and lifecycle methods, and gauge how to effectively integrate your user interface components with other JavaScript libraries. Delve deep into the core elements of the Redux architecture and learn how to manage your application and data persistence. Then go the extra mile with the Jest test framework, and run multiple tests on your applications and find solutions to scale without complexity. Today React is used by Facebook, Instagram, Khan Academy, and Imperial College London, to name a few. Many new users recognize the benefits of React and adopt it in their own projects, forming a fast-growing community. The speed at which React has evolved promises a bright future for anyone who invests in learning it today. Let Artemij and Adam bring you a brand new look at React 16 and React Fiber, and move your web development into the future.

What you will learn

Learn to code React 16 with hands-on examples and clear tutorials Install powerful React 16 tools to make development much more efficient Understand the impact of React Fiber today and the future of your web development Utilize the Redux application architecture with your React components Create React 16 elements with properties and children Get started with stateless and stateful React components Use JSX to speed up your React 16 development process Add reactivity to your React 16 components with lifecycle methods Test your React 16 components with the Jest test framework

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Nov 30, 2017
Length 240 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781787126046
Vendor :
Facebook
Category :

Table of Contents

20 Chapters
React 16 Essentials Second Edition Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Authors Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Customer Feedback Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. What's New in React 16 Chevron down icon Chevron up icon
2. Installing Powerful Tools for Your Project Chevron down icon Chevron up icon
3. Creating Your First React Element Chevron down icon Chevron up icon
4. Creating Your First React Component Chevron down icon Chevron up icon
5. Making Your React Components Reactive Chevron down icon Chevron up icon
6. Using Your React Components with Another Library Chevron down icon Chevron up icon
7. Updating Your React Components Chevron down icon Chevron up icon
8. Building Complex React Components Chevron down icon Chevron up icon
9. Testing Your React Application with Jest Chevron down icon Chevron up icon
10. Supercharging Your React Architecture with Flux Chevron down icon Chevron up icon
11. Preparing Your React Application for Painless Maintenance with Flux Chevron down icon Chevron up icon
12. Refining Your Flux Apps with Redux Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.