What's New in React v16.6

joshtronic

Less than 2 months since the initial release of React v16.5, the great folks over on the React Team have bestowed upon us the 101st release of React. This latest release introduces some new API additions in React.lazy(), React.memo(), and contextType and even introduces a new life cycle method, getDerivedStateFromError.

Keep in mind that this is a minor release to v16 so if you’re already on a version of said major version, upgrading should give minimal migraines.

Let’s take a look at these shiny new offerings!

React.lazy()

React.lazy() allows you to load components only when they need to be rendered, a/k/a lazy loading. This allows you to reduce your bundle size and while today it’s something you can do with the likes of Webpack, it’s pretty awesome to see it baked right into React.

// React <= v16.5
import ImmediatelyLoadedComponent from './ImmediatelyLoadedComponent';

// React v16.6+
import { lazy } from 'react';
const LazyLoadedComponent = lazy(() => import('./LazyLoadedComponent'));

But wait, there’s more. You can combine React.lazy() with Suspense and specify a fallback component that will show while the dynamically loaded component is being loaded.

import { lazy, Suspense } from 'react';
const LazyLoadedComponent = lazy(() => import('./LazyLoadedComponent'));

function App() {
  return (
    <Suspense fallback={<div>Please wait while we lazy load...</div>}>
      <LazyLoadedComponent />
    </Suspense>
  );
}

Should cut down on a ton of “loading” boilerplate code as well! For more on the highly anticipated React Suspense, check out this popular talk given by Dan Abramov at JSConf Iceland 2018.

Please keep in mind that React.lazy() and Suspense aren't quite ready for server-side rendering, but will be available in the future.

React.memo()

Function components are great when you don’t need to manage state but this lack of lifecyle methods means you aren’t able to define shouldComponentUpdate. Without that, your component is always going to re-render.

Similar to React.PureComponent, React.memo() is a higher order component that allows you to skip re-renders when a function component’s props are the same:

const Component = React.memo(function (props) { });

Out of the box, React.memo() only does a shallow compare on the props object. If you need something more advanced, you can pass a comparison function as the second parameter to React.memo():

const Component = React.memo(function (props) { }, (prevProps, nextProps) => {
  // Return true if equal, false if not
});

contextType

Ah the saga of the Context API. At one point it was available, but usage was discouraged. Then in React v16.3 an official Context API was added. Now in React v16.6 it’s even easier to consume the context value anywhere within class components:

import React, { Component } from 'react';

const GatorContext = React.createContext('American');

class Alligator extends Component {
  static contextType = GatorContext;

  componentDidMount() {
    const contextValue = this.context;
    // Do some stuff with the context value
  }

  componentWillReceiveProps() {
    const contextValue = this.context;
    // Do some other stuff with the context value
  }

  render() {
    const contextValue = this.context;
    // Conditionally render based on the context value
  }
}

getDerivedStateFromError

One of the great additions that made it into React v16 has been Error Boundaries which helps ease the previous pain points with dealing with errors in React render methods.

In additional to componentDidCatch, React v16.6 introduces the getDerivedStateFromError life cycle method. Unlike it’s counterpart, which is intended for error logging, getDerivedStateFromError receives an error and is intended to return a value to update state:

import React, { Component } from 'react';

class GatorError extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.error) {
      return <div>Something borked :(</div>;
    }
    // If these kids act up, we'll know!
    return this.props.children;
  }
}

Similar to React.lazy(), getDerivedStateFromError is not currently available for server-side rendering, but will be in the future.

Deprecations

Also worth noting, there are a small handful of new deprecations in v16.6 that you should be aware of, especially if you like to keep your code base tidy as things in React-land shift around:

  • ReactDOM.findDOMNode() - For all intents and purposes, you really should be leveraging the power of React instead of rooting around in the DOM. As it turns out, this method is also crazy slow in React v16.
  • Legacy Context - Now that we have an official Context API, it only makes sense that we should stop using contextTypes and getChildContext.

These deprecations will only show up if you’re using the StrictMode component. If not, you won’t see these in your logs. Still worth being aware of though ;)

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#