Sign Up
Hero

React 16.3: What’s New?

Learn about the new features in React 16.3. New Lifecycles, Context, Strict Mode, createRef, and forwardRef

ReactJS 16 shipped with a lot of new features. Since then, even more features have been introduced to the library.

React 16.3 ships with a few major changes that I'll like to highlight in this article. Let's dive in!

StrictMode Component

JavaScript developers are very familiar with the strict keyword. This keyword keeps you in check while developing your apps and raises an alarm during development to let you know about potential problems in your codebase.

React 16.3 ships with a StrictMode component that highlights potential problems in your ReactJS codebase.

This component runs a check in development mode to determine if there are issues with the descendant components such as using an unsafe lifecycle method, legacy ref API, etc.

import React from 'react';

function WokeAlarm() {
  return (
    <div>
      <Header />
      <React.StrictMode>
        <div>
          <SetAlarm />
          <RingAlarm />
        </div>
      </React.StrictMode>
      <Footer />
    </div>
  );
}

New Lifecycle Methods

React 16.3 ships with new lifecycle methods such as getDerivedStateFromProps, and getSnapshotBeforeUpdate.

The current lifecycle methods componentWillMount, componentWillReceiveProps, and componentWillUpdate will be deprecated in a future ReactJS 16.x release because they have been known to be problematic and behave in unintended ways. These methods will continue to be available for use in the next major release, React 17.

  • getDerivedStateFromProps can be used instead of componentWillReceiveProps.
  • componentDidMount can be used instead of componentWillMount.
  • componentDidUpdate can be used instead of componentWillUpdate.

The new getDerivedStateFromProps method is static and will be called on the initial mounting of the component and also when the component is re-rendered.

"The new getDerivedStateFromProps method is static and will be called on the initial mounting of the component."

Tweet This

class Speaker extends Component {
  static getDerivedStateFromProps() {
    if (nextProps.value !== prevState.value) {
      return ({ value: nextProps.value });
    }
  }
}

The new getSnapshotBeforeUpdate method is called before any DOM mutations happen. It's great to perform any sort of calculations needed for your component here and then pass it to componentDidUpdate as the third argument like so:

"The new getSnapshotBeforeUpdate method is called before any DOM mutations happen."

Tweet This

...
getSnapShotBeforeUpdate(prevProps, prevState) {
  return prevProps.list.length < this.props.list.length ? this.listRef.scrollHeight : null;
}

componentDidUpdate(prevProps, prevState, snapshot) {
  if (snapshot !== null) {
    const listRef = this.listRef;
    listRef.scrollTop += listRef.scrollHeight - snapshot;
  }
}
...

forwardRef

Refs provide a way to access ReactJS elements or DOM nodes created in the render method. They are great for getting values from input elements, working with third-party DOM libraries, et al. However, there were some challenges with refs regarding component encapsulation.

forwardRef automatically passes a ref received by a parent component to its children. It's great for reusable components in component libraries. As the name implies, the component is forwarding the ref to its child.

Check out the example below:

import React, { Component } from 'react';

const LoginButton = React.forwardRef((props, ref) => (
  <button ref={ref} class="Login"> {props.children} </button>
));


class Display extends Component {
  myRef = React.createRef();

  componentDidMount() {
    this.myRef.current.focus();
  }

  render() {
    return (
      <div className="container">
        <LoginButton ref={this.myRef}> Get In! </LoginButton>
      </div>
    )
  }
}

The use of forwardRef is more valuable in Higher Order Components. The ReactJS blog has the perfect example of this scenario.

createRef

Previously, ReactJS developers had two ways of using refs: You either made use of the callback API or the legacy string ref API.

With React 16.3, you can make use of the createRef API for managing refs without any negative implications. It's simpler and developer friendly too. Check out the example below:

without createRef API

class SpeakerComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <input type="text" ref={(input) => {
      this.inputRef = input;
    }} />;
  }
}

with createRef API

class SpeakerComponent extends React.Component {
  constructor(props) {
    super(props);

    this.inputRef = React.createRef();
  }

  render() {
    return <input type="text" ref={this.inputRef} />;
  }

  componentDidMount() {
    this.inputRef.current.focus();
  }
}

Context API

The Context API has been available for a while but in experimental mode. React 16.3 ships with an ergonomic Context API that supports static type checking and deep updates. This API solves the challenge most developers experience which is the complexity of passing data from child to parent and back and make them quickly reach out for Redux.

Check out this example below:

import React, { Component } from 'react';

const Dog = (props) => (
  <div>
    <Animal name={props.name} />
  </div>
);

}
class Animal extends Component {
  render() {
    return (
      <div>
        <p> Hey, I'm a {this.props.name} </p>
      </div>
    )
  }
}


class App extends Component {
  state = {
    name: 'Casanova',
    food: 'bone',
  }

  render() {
    return (
      <div>
        <Dog name={this.state.name} />
      </div>
    )
  }
}

export default App;

This is a simple example, but the way we pass data from component to component with the use of props is not developer friendly and could get out of hand very quickly! At this point, most developers quickly reach out for a data store or state management library to manage this process efficiently. However, the new Context API in React 16.3 can be used to eliminate this challenge.

With this new API, we'll need a Provider and a Consumer. The data will live in the Provider while the Consumer represents where the data needs to be accessed.

import React, { Component } from 'react';

// create a new context
const MyContext = React.createContext();

// create a provider component
class MyProvider extents Component {
  state = {
    name: 'Casanova',
    food: 'bone'
  }

  render() {
    return (
      
      <MyContext.Provider value={{ state: this.state }}>
        { this.props.children }
      </MyContext.Provider>
      
    )
  }
}

const Dog = (props) => (
  <div>
    <Animal />
  </div>
);

class Animal extends Component {
  render() {
    return (
      <div>
        <MyContext.Consumer>
          {(context) => (
            <React.Fragment>
              <h3> Food: { context.state.food } </h3>
              <h3> Name: { context.state.name } </h3>
            </React.Fragment>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}

class App extends Component {
  render() {
    return (
      <MyProvider>
        <div>
          <Dog />
        </div>
      </MyProvider>
    )
  }
}

export default App;

In the code above, there is a provider, <MyProvider />, that houses the state and renders a Context provider.

The Context provider provides the ability to render children components as evident in the <App /> component. We simply called the consumer, <MyContext.Consumer />, in the Animal component to render the data we needed. This is more organized, and avoids the case of props drilling hell!

Aside: Securing React Apps with Auth0

As you will learn in this section, you can easily secure your React applications with Auth0, a global leader in Identity-as-a-Service (IDaaS) that provides thousands of enterprise customers with modern identity solutions. Alongside with the classic username and password authentication process, Auth0 allows you to add features like Social Login, Multifactor Authentication, Passwordless Login, and much more with just a few clicks.

To follow along the instruction describe here, you will need an Auth0 account. If you don't have one yet, now is a good time to sign up for a free Auth0 account.

Also, if you want to follow this section in a clean environment, you can easily create a new React application with just one command:

npx create-react-app react-auth0

Then, you can move into your new React app (which was created inside a new directory called react-auth0 by the create-react-app tool), and start working as explained in the following subsections.

Setting Up an Auth0 Application

To represent your React application in your Auth0 account, you will need to create an Auth0 Application. So, head to the Applications section on your Auth0 dashboard and proceed as follows:

  1. click on the Create Application button;
  2. then define a Name to your new application (e.g., "React Demo");
  3. then select Single Page Web Applications as its type.
  4. and hit the Create button to end the process.

After creating your application, Auth0 will redirect you to its Quick Start tab. From there, you will have to click on the Settings tab to whitelist some URLs that Auth0 can call after the authentication process. This is a security measure implemented by Auth0 to avoid the leaking of sensitive data (like ID Tokens).

So, when you arrive at the Settings tab, search for the Allowed Callback URLs field and add http://localhost:3000/callback into it. For this tutorial, this single URL will suffice.

That's it! From the Auth0 perspective, you are good to go and can start securing your React application.

Dependencies and Setup

To secure your React application with Auth0, there are only three dependencies that you will need to install:

  • auth0.js: This is the default library to integrate web applications with Auth0.
  • react-router: This is the de-facto library when it comes to routing management in React.
  • react-router-dom: This is the extension to the previous library to web applications.

To install these dependencies, move into your project root and issue the following command:

npm install --save auth0-js react-router react-router-dom

Note: As you want the best security available, you are going to rely on the Auth0 login page. This method consists of redirecting users to a login page hosted by Auth0 that is easily customizable right from your Auth0 dashboard. If you want to learn why this is the best approach, check the Universal vs. Embedded Login article.

After installing all three libraries, you can create a service to handle the authentication process. You can call this service Auth and create it in the src/Auth/ directory with the following code:

// src/Auth/Auth.js
import auth0 from 'auth0-js';

export default class Auth {
  constructor() {
    this.auth0 = new auth0.WebAuth({
      // the following three lines MUST be updated
      domain: '<AUTH0_DOMAIN>',
      audience: 'https://<AUTH0_DOMAIN>/userinfo',
      clientID: '<AUTH0_CLIENT_ID>',
      redirectUri: 'http://localhost:3000/callback',
      responseType: 'token id_token',
      scope: 'openid profile',
    });

    this.getProfile = this.getProfile.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.setSession = this.setSession.bind(this);
  }

  getProfile() {
    return this.profile;
  }

  handleAuthentication() {
    return new Promise((resolve, reject) => {
      this.auth0.parseHash((err, authResult) => {
        if (err) return reject(err);
        console.log(authResult);
        if (!authResult || !authResult.idToken) {
          return reject(err);
        }
        this.setSession(authResult);
        resolve();
      });
    });
  }

  isAuthenticated() {
    return new Date().getTime() < this.expiresAt;
  }

  login() {
    this.auth0.authorize();
  }

  logout() {
    // clear id token and expiration
    this.idToken = null;
    this.expiresAt = null;
  }

  setSession(authResult) {
    this.idToken = authResult.idToken;
    this.profile = authResult.idTokenPayload;
    // set the time that the id token will expire at
    this.expiresAt = authResult.expiresIn * 1000 + new Date().getTime();
  }
}

The Auth service that you just created contains functions to deal with different steps of the sign in/sign up process. The following list briefly summarizes these functions and what they do:

  • getProfile: This function returns the profile of the logged-in user.
  • handleAuthentication: This function looks for the result of the authentication process in the URL hash. Then, the function processes the result with the parseHash method from auth0-js.
  • isAuthenticated: This function checks whether the expiry time for the user's ID token has passed.
  • login: This function initiates the login process, redirecting users to the login page.
  • logout: This function removes the user's tokens and expiry time.
  • setSession: This function sets the user's ID token, profile, and expiry time.

Besides these functions, the class contains a field called auth0 that is initialized with values extracted from your Auth0 application. It is important to keep in mind that you have to replace the <AUTH0_DOMAIN> and <AUTH0_CLIENT_ID> placeholders that you are passing to the auth0 field.

Note: For the <AUTH0_DOMAIN> placeholders, you will have to replace them with something similar to your-subdomain.auth0.com, where your-subdomain is the subdomain you chose while creating your Auth0 account (or your Auth0 tenant). For the <AUTH0_CLIENT_ID>, you will have to replace it with the random string copied from the Client ID field of the Auth0 Application you created previously.

Since you are using the Auth0 login page, your users are taken away from the application. However, after they authenticate, users automatically return to the callback URL that you set up previously (i.e., http://localhost:3000/callback). This means that you need to create a component responsible for this route.

So, create a new file called Callback.js inside src/Callback (i.e., you will need to create the Callback directory) and insert the following code into it:

// src/Callback/Callback.js
import React from 'react';
import { withRouter } from 'react-router';

function Callback(props) {
  props.auth.handleAuthentication().then(() => {
    props.history.push('/');
  });

  return <div>Loading user profile.</div>;
}

export default withRouter(Callback);

This component, as you can see, is responsible for triggering the handleAuthentication process and, when the process ends, for pushing users to your home page. While this component processes the authentication result, it simply shows a message saying that it is loading the user profile.

After creating the Auth service and the Callback component, you can refactor your App component to integrate everything together:

// src/App.js

import React from 'react';
import { withRouter } from 'react-router';
import { Route } from 'react-router-dom';
import Callback from './Callback/Callback';
import './App.css';

function HomePage(props) {
  const { authenticated } = props;

  const logout = () => {
    props.auth.logout();
    props.history.push('/');
  };

  if (authenticated) {
    const { name } = props.auth.getProfile();
    return (
      <div>
        <h1>Howdy! Glad to see you back, {name}.</h1>
        <button onClick={logout}>Log out</button>
      </div>
    );
  }

  return (
    <div>
      <h1>I don't know you. Please, log in.</h1>
      <button onClick={props.auth.login}>Log in</button>
    </div>
  );
}

function App(props) {
  const authenticated = props.auth.isAuthenticated();

  return (
    <div className="App">
      <Route
        exact
        path="/callback"
        render={() => <Callback auth={props.auth} />}
      />
      <Route
        exact
        path="/"
        render={() => (
          <HomePage
            authenticated={authenticated}
            auth={props.auth}
            history={props.history}
          />
        )}
      />
    </div>
  );
}

export default withRouter(App);

In this case, you are actually defining two components inside the same file (just for the sake of simplicity). You are defining a HomePage component that shows a message with the name of the logged-in user (that is, when the user is logged in, of course), and a message telling unauthenticated users to log in.

Also, this file is making the App component responsible for deciding what component it must render. If the user is requesting the home page (i.e., the / route), the HomePage component is shown. If the user is requesting the callback page (i.e., /callback), then the Callback component is shown.

Note that you are using the Auth service in all your components (App, HomePage, and Callback) and also inside the Auth service. As such, you need to have a global instance for this service, and you have to include it in your App component.

So, to create this global Auth instance and to wrap things up, you will need to update your index.js file as shown here:

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import Auth from './Auth/Auth';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

const auth = new Auth();

ReactDOM.render(
  <BrowserRouter>
    <App auth={auth} />
  </BrowserRouter>,
  document.getElementById('root'),
);
registerServiceWorker();

After that, you are done! You just finished securing your React application with Auth0. If you take your app for a spin now (npm start), you will be able to authenticate yourself with the help of Auth0, and you will be able to see your React app show your name (that is, if your identity provider does provide a name).

If you are interested in learning more, please, refer to the official React Quick Start guide to see, step by step, how to properly secure a React application. Besides the steps shown in this section, the guide also shows:

Conclusion

React 16 has been on a roller-coaster. And it's amazing how ReactJS is becoming more of a way of life than a library, in my opinion.

Have you upgraded to React 16.3 yet? What are your thoughts? Let me know in the comments section! 😊