React 16.3(.0-alpha)-A Gradual Migration Strategy

by Arun Kumar

on May 16, 2018

Introduction

In React 16.3.0, includes addition of a few new lifecycle methods to assist with that migration. It introduces new APIs for long requested features: an official context API, a ref forwarding API, and an ergonomic ref API.

The Alpha release concerns deprecation of some life-cycle methods and introduction of one (four) new.

The functions that will be in time considered deprecation are:

  • componentWillMount — please use componentDidMount instead
  • componentWillUpdate — please use componentDidUpdate instead
  • componentWillReceiveProps — a new function, static getDerivedStateFromProps is introduced

The deprecation notices if you also opt in into the new StrictMode or AsyncMode in which case you can still suppress them by using:

  • UNSAFE_componentWillMount
  • UNSAFE_componentWillReceiveProps
  • UNSAFE_componentWillUpdate

Deprecation warnings will be enabled with a future 16.x release, but the legacy lifecycles will continue to work until version 17.

Even in version 17, it will still be possible to use them, but they will be aliased with an “UNSAFE_” prefix to indicate that they might cause issues.

static getDerivedStateFromProps

As componentWillReceiveProps gets removed, we need some means of updating the state based on props change — the community decided to introduce a new — static — method to handle this.

A static method is a method / function that exists on the class not its instance. The easiest difference to think about is that static method does not have access to this and has the keyword static in front of it.

Without keyword static, the alternative syntax:

ComponentName.getDerivedStateFromProps=(nextProps,prevState)=>{}

Using get DerivedStateFromProps in order to update state:

 static getDerivedStateFromProps(nextProps,prevState){

if(nextProps.firstData===prevState.firstData){

return null

}

return{

firstData:nextProps.firstData

}

}

Main feature on getDerivedStateFromProps:

getDerivedStateFromProps is called both on initial mounting and on re-rendering of the component, so you can use it instead of creating state based on props in constructor.

static getSnapshotBeforeUpdate

getSnapshotBeforeUpdate is being added to support safely reading properties from e.g. the DOM before updates are made.

Subscribe to our Newsletter

  • Share this Article

GET IN TOUCH WITH iLEAF

  • We can initiate development process at the hour of your convenience
  • Discussion on the projects can be held for a stipulated duration
  • We will sign NDA and the talks will be secured
  • We’ll show you around our cherished designs
  • Briefing on technology
  • Guaranteed source code delivery
  • Option to re-start a closed venture

See how we can unwrap your app idea and proceed towards success