What’s New in React 16

Introduction

Facebook recently announced the release of React 16, a complete rewrite of the React library. The new core architecture, code-named Fiber, keeps most of the API intact and backward compatible, so you can update existing apps without running into issues. Fiber introduces lots of new highly anticipated features and improvements to React. This blog post is about what’s new in React 16. It will cover the new features that lets React developers catch and handle JavaScript errors in React components; render elements into different locations in the DOM outside of the main component tree using portals; return multiple elements without having to wrap them in a parent element using new render return types like arrays, strings and numbers; also return null from setState to prevent unnecessary state updates and re-renders and more.

You can start using React 16 today. When you install React in a project or create a new app using the create-react-app tool, it will automatically install the latest version of React and ReactDOM. As mentioned above, React 16 is backwards compatible. So if you are currently running your app on a previous version of React without any console errors or deprecation warnings, updating to React 16 will not break your app. It should be a seamless transition. Now with a complete rewrite of the React Library comes a few minor breaking changes that only affect uncommon use cases. You can view all the breaking changes. A welcome change is that React is now available under the MIT license. The uncertainties created by Facebook’s previous BSD+Patent’s open source license was a concern to many developers, startups and companies using React. So now React licensing is more flexible. You can use React in your project without having to worry about the previous patent’s clause. Now if you are not able to upgrade immediately to version 16, React 15.6.2, was also published under MIT. Also note, the React 16 update does not mean that whatever you have learned so far about React is immediately obsolete. The API itself hasn’t changed, and most of the skills you have learned are still important, fundamental skills you will continue to use. So if you are eager to learn about everything that is new in React 16 next I will cover the new component life cycle method and error handling feature that lets us catch and manage errors when rendering React components.

Take Control of Errors with componentDidCatch()

One of the biggest changes in React 16 is how React handles JavaScript errors. Normally, a JavaScript error inside a component, for example, like an uncaught type error will break the entire app. A JavaScript error in a part of the UI shouldn’t break the whole app. So in React 16 error handling was improved to avoid these types of situations where runtime errors during rendering breaks your app. It provides a built-in solution for handling errors gracefully with a new life cycle method called componentDidCatch(). This life cycle hook gets triggered whenever a childs component render or life cycle methods throw an error. When an error occurs, componentDidCatch() catches the error and instead of crashing the entire app, the app continues to run as normal displaying all the UI except for the faulty component. You can even display a fallback UI to replace the component that crashed.

Catching Errors with Error Boundaries

With the componentDidCatch() lifecycle method comes a new concept of an error boundary. Error boundaries are wrapper components that use componentDidCatch() to capture errors anywhere in their child component tree and display a fallback UI in its place. They provide an easier way to keep the error catching and conditional rendering logic reusable and maintainable in your app. You create an error boundary as a class component. Any errors caught in the component tree get reported up to the Error Boundary’s componentDidCatch() method thereby providing a handy way of sending error reports to an error tracking or monitoring service. The componentDidCatch() method take two arguments to help you track and investigate errors, error – the error instance itself, and info which contains the component stack trace or the path in the component tree leading up to the offending component. The component stack trace contains helpful information for sorting and resolving errors. The componentDidCatch() method and Error Boundary work like try/catch statements for your React components. They provide a more consistent and dependable way to catch and deal with errors.

Note: Error Boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.

New Return Types

React 16 supports new return types that let your render less DOM nodes. For example, React no longer requires that the render() method returns a single React element. You are able to render multiple sibling elements without a wrapping element by returning an array. The other new return types React 16 supports are strings and numbers. Eliminating divs or any extra element added just to wrap your React component tree or returned content leads to overall cleaner and smaller components.

Render Children into Other DOM Nodes with Portals

React 16 introduces a new way of rendering into the DOM. You can render children into a DOM element that exists outside of your apps main DOM tree with a new feature called Portals. For example, in your index.html template you will usually have a div with the id root which is where your entire app is rendered into the DOM via ReactDOM.render. To create a portal, you add a second element that’s a sibling of your root div as shown below.

<div id="root"></div>
<div id="my-portal"></div>

Then you can render specific parts of your component tree inside the sibling div with the new createPortal() function. The createPortal(child, container) function accepts two arguments, child and container. The first argument child is the content you want to render. The second argumnet container is the DOM element where the content is going to render. createPortal() provides a hook into HTML that’s outside the root div. As mentioned in React docs, portals are useful when a parent component has an overflow hidden or z-index style, but you need the child to visually break out of its container. So a handy use case for portals is when creating modal windows or overlays. What’s interesting about portals is that the components they render are recognized as regular child components of the app. In other words, even though portal can be anywhere in the DOM tree, it behaves like a normal React child in every other way. For example, an event triggered from inside a portal still propagates or bubbles up to the parent component.

Returning null from setState

React 16 lets you decide if state gets updated via setState to prevent unnecessary DOM updates. In your events you can check if the new value of the state is the same as the existing one. If the values are the same, you can return null. Returning null will not update state and trigger a re-render. React 16 provides state performance improvements that let you prevent an update from being triggered by returning null for setState if the new value of state is the same as the existing value. Preventing unnecessary state updates and re-renders with null can make your app perform faster.

So these are some of the most important updates to React 16. Now there are a few other features I didn’t cover above like support for custom DOM attributes and Better server-side rendering. Finally, as with many popular JavaScript libraries, React is going to be updated frequently. Happy Coding!!!

Resources

Webpack

In this post I will talk about Webpack a very popular build tool in the React community. Now if you are used to tools like Grunt or Gulp you can think of Webpack as being something similar. Now Grunt and Gulp are general purpose task runners. So they can technically do what Webpack can do but requires configuring a bunch of plugins. Webpack on other hand is a complete Module Bundler. So what’s a module bundler?

Now if you look at any React project or for that matter any web project, it contains a bunch of static assets like JavaScript, CSS, Sass files, Images, Fonts and so on. Each of these in the Webpack parlance is called a module. These modules can depend on each other. Webpack being a module bundler, combines all of these modules into a highly optimized bundle which can then be deployed onto the web. Webpack also takes care of automatically bundling these modules anytime they change which gives us a nice development time workflow.

Now if we probe a little deeper into Webpack, we will see 3 fundamental concepts – Loader, Plugin and Chunk. A Loader is responsible for loading a single file and also optionally transforming it. As an example, we have the Sass loader which loads the Sass files and transforms it to CSS. A Plugin can extend the behavior of Webpack and also operate on multiple files at once. As an example, we have the HTML Webpack plugin which can create the index.html based on all the bundles we have in a project. Lastly, Chunk is the output of Webpack. There could be more than one chunk created depending on how the project is structured. Loaders and Plugins can both contribute in creating the Chunk, also known as the Bundle.

React Life Cycle

This post covers some of the key concepts in React – props, state and keys. Then I will talk about React’s multiple life cycle functions which give us hooks for initializing our components and attaching behaviors at specific points in time.

Data for a given React component is held in two places, props and state.

Props is short for properties. We can think of properties a lot like HTML attributes. Props allow us to pass data down to child components. Props are immutable since they are passed down from the parent, they are effectively owned by the parent.

State in contrast is mutable and since state is mutable we should only strive to utilize state on our controller views. In other words, only use state on the top level components. Pass data down to your child components via props.

getInitialState – We can optionally define a getInitialState function. In this function, we can set the initial state for our component. This should typically only be done in the top level component, also known as our controller view.

getDefaultProps – We can also define default values for properties on our components using the getDefaultProps method. Inside this method, we can return a set of properties that our component should use by default if the parent component doesn’t declare a value.

React’s Life Cycle Methods

componentWillMount
When – Runs immediately before initial rendering. Runs both on the client and server.
Why – This function is a great spot to set the component’s initial state.

componentDidMount
When – Runs immediately after render.
Why – By the time this function is called, the component’s DOM exists. So this is a handy spot for integrating with other frameworks such as third party component libraries. This is also a good spot to set timers and make AJAX requests since you now know the component is rendered in the DOM.

componentWillReceiveProps
When – Run when the component is receiving new properties. In other words, when properties have changed. Not called on initial render.
Why – This is a place to set state before the next render since this runs just before the new properties are received.

shouldComponentUpdate
When – Runs immediately before render and when props or state are being received by your component.
Why – The big reason this function is useful is for performance. Why? Well, sometimes props and/or state changes, but the component doesn’t actually need to re-render because the data change doesn’t affect the DOM. When this is the case, you can return false from this function to avoid an unnecessary render call.

componentWillUpdate
When – Runs immediately before rendering when new props or state are being received. Not called on initial render.
Why – This function is a useful place to prepare for an update. However, do note, we cannot call setState in this function.

componentDidUpdate
When – Is evoked immediately after the component’s updates are flushed to the DOM. Not called for the initial render.
Why – This function allows us to operate on the DOM immediately after the component has been updated and re-rendered in the DOM.

componentWillUnmount
When – This function runs just before the component is unmounted/removed from the DOM.
Why – This is a great place to cleanup by destroying any related resources or DOM elements that were created when the component was mounted.

Keys for Dynamic Children

When creating multiple child components dynamically, we need to provide a key for each child component. The key is often the primary key for the corresponding database record, but it need not be. We just need to declare a unique ID for each specific record. As child components are added and removed, React uses this key to assure that child components are properly reordered or destroyed.