React 16.3(.0-alpha)-A Gradual Migration Strategy
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:
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.
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:
Using get DerivedStateFromProps in order to update state:
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.
getSnapshotBeforeUpdate is being added to support safely reading properties from e.g. the DOM before updates are made.
Subscribe to our Newsletter