Why you should update to React 16

What’s new in React 16?

The new version of React 16 comes with a lot of new features and improvements to stability.
Facebook, the company behind React, has rewritten the entire core architecture making it able to support long-awaited features.
In this post, we will explore the changes, and how to migrate to react 16 from previous versions.

Improvements

  • New engine for server-side rendering
  • Library size reduce almost 35%
  • New core architecture – support for async rendering
  • Support for code splitting

New Features

Fragments

With fragments now we can return a set of components, or array, without having to wrap them in a container such as a div.

class MyComponent extends React.Component {  
 render() {  
   return (  
     <>  // <--- Notice this new JSX syntax  
       <div>Fragments</div>  
       <div>Are</div>
       <div>Awesome</div>  
     </>  
   );  
 }  
}

This will help to reduce the amount of DOM elements in your application.

Which will improve the page speed reliability.

Error Boundaries

Before error boundaries, when javascript threw errors it used to corrupt React’s internal state, causing strange error messages on render.

The error boundaries components catch Javascript errors in the child component tree. 

Also, it logs the errors and displays a fallback UI.

To create an error boundary, implement a class component with the methods static getDerivedStateFromError and componentDidCatch.

class ErrorHandler extends React.Component {  
 constructor(props) {  
   super(props);  
    this.state = { hasError: false };  
 }  
 static getDerivedStateFromError(error) {  
   // Update state so the next render will show the fallback UI.  
   return { hasError: true, error };  
 }  
 componentDidCatch(error, info) {  
   // You can also log the error to an error reporting service  
   console.log(error, info);  
 }  
 render() {  
   if (this.state.hasError) {  
     // You can render any custom fallback UI  
     return (
      <div>
      <p>Something terrible happened.</p>
      <p>  { this.state.error } </p>
      </div>
    );  
   }  
   return this.props.children;  
 }  
}

Now you can wrap your app inside the ErrorHandler component.

class MyApp extends Component {
 render() {
  return (
    <ErrorHandler> 
      <App />
    </ErrorHandler>
  )
 }
}

You can think them as try {…} catch(e) {…} blocks but for components.

Be aware that only class components can be error boundaries.

Portals

A concept that has been around for a while.

Provides the ability to render children into a DOM node that is not inside the DOM of the parent component

It’s a useful feature for cases where the CSS styles are holding back your components (overflow issues, stacking z-index).

You can even render components in a new window.

const Modal = () => {
 ReactDom.createPortal(<div> This modal it's outside the DOM   hierarchy !!</div>, document.body)
}

class MyApp extends Component {
 render() {
  return <Modal />
 }
}

React Hooks

A way to make stateful components stateless, by moving away from the logic from the component.

They let you use state without writing a class.

import React, { useState } from 'react';  

function Example() {  
 const [count, setCount] = useState(0);  

 // Similar to componentDidMount and componentDidUpdate:  
 useEffect(() => {  
   // Update the document title using the browser API  
   document.title = `You clicked ${count} times`;  
 });  

 return (  
   <div>  
     <p>You clicked {count} times</p>  
     <button onClick={() => setCount(count + 1)}>  
       Click me  
     </button>  
   </div>  
 );  
}

Now the component ‘ behavior’ that was on componentDidMount and componentDidUpdate can be isolated in simple Javascript functions.

This helps to reuse the logic, now several components can share the logic.

And now that theay are just fucntions, writing unit tests becomes less complex.

How to update my app to React 16?

Now that we discuss the benefits of React 16, you may be wondering how to upgrade your app to React 16

If you happened to have your React App with a version 15.6 and your application doesn’t show any warnings, the process is pretty straight forward.
Update the dependecies of react and react-dom to 16
npm install --save react@16.6.0 react-dom@16.6.0

Before doing any update, it’s always a recommend to have unit tests to ensure a correct transition without breaking any components.

For more information, read to our guide to Writing unit tests with Jest for React components 

Upgrade to React 16 from <React 15.5

If you are using a version previous to React 15.6, the first step is to upgrade to React 15.6 and solve the deprecation warnings if you have anyone.

npm install --save react@^15.6.0 react-dom@^15.6.0

After upgrading the package.json dependencies to React 15.6, and ONLY if you are not using ES6.

The next step is refactor the calls to React.createClass for the new individual package from npm.

But if you are using ES6 with the class syntax you don’t have to do anything

// Before (15.4 and below)  
var React = require('react');  
var Component = React.createClass({  
 render() {  
   return <Child />;  
 }  
});  

// After (15.5)  
var React = require('react');  
var createReactClass = require('create-react-class');  
var Component = createReactClass({  
 render() {  
   return <Child />;  
 }  
});

// Remains unchanged
class Greeting extends React.Component {  
 render() {
   return <h1>Thanks for reading our blog!</h1>;  
 }  
}

Now proceed to upgrade to react 16 as described before.

Conclusion

Certainly, React 16 is a huge update that you will benefit from having. Especially the new error handler for component and the new API React Hooks.

Finally, while there are some minor breaking changes, the react dev team don’t expect them to break most of the apps out there.

Leave a Reply

Your email address will not be published. Required fields are marked *