Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
React 16 Essentials
React 16 Essentials

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

Arrow left icon
Profile Icon Pitt Profile Icon Artemij Fedosejev Profile Icon Adam Boduch
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (2 Ratings)
Paperback Nov 2017 240 pages 2nd Edition
eBook
NZ$14.99 NZ$38.99
Paperback
NZ$48.99
Subscription
Free Trial
Arrow left icon
Profile Icon Pitt Profile Icon Artemij Fedosejev Profile Icon Adam Boduch
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (2 Ratings)
Paperback Nov 2017 240 pages 2nd Edition
eBook
NZ$14.99 NZ$38.99
Paperback
NZ$48.99
Subscription
Free Trial
eBook
NZ$14.99 NZ$38.99
Paperback
NZ$48.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

React 16 Essentials

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:

Running to completion

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:

Running to completion

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.

Who is this book for?

If you're a frontend developer with some knowledge of native JavaScript development and frontend frameworks, wishing to learn the fastest web user interface library there is, then this book is ideal for you.

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

Product Details

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

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 192.97
React 16 Essentials
NZ$48.99
Progressive Web Apps with React
NZ$71.99
React Design Patterns and Best Practices
NZ$71.99
Total NZ$ 192.97 Stars icon
Banner background image

Table of Contents

13 Chapters
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

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(2 Ratings)
5 star 0%
4 star 50%
3 star 0%
2 star 50%
1 star 0%
Marco Jan 05, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
It's a very good book. I already read the previous edition where there are some concepts no more used neither in the official React documentation (but for me still usefull). The book is well organized and it brings you to understand the essential parts of React. I read several books about React but this one is one of the one clearest.Just one "technical question" that I would like to make to the author: why he doesn't present stateless components as functions?Anyway, a good book. I suggested it.
Amazon Verified review Amazon
Ahsan J. Sharafuddin Jun 21, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The book is hard to follow. The code is not clearly stated and I couldn't get it to work for me. Had to give up half way through the book. I think the author unnecessarily complicates the topics. There are plenty of good books available on the market on the subject. I am immensely enjoying 'React Quickly'.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.