React works in two phases: render and commit.
componentDidMount and componentDidUpdate during this phase. Render phase lifecycles include among others, the following lifecycle methods:
componentWillMount (or its alias UNSAFE_componentWillMount) componentWillReceiveProps (or its alias UNSAFE_componentWillReceiveProps) componentWillUpdate (or its alias UNSAFE_componentWillUpdate) These are considered unsafe and also happen to be the lifecycles that cause the most confusion within the React community and tend to encourage unsafe coding practices.
class Foo extends React.Component {
UNSAFE_componentWillMount() {} // Noncompliant
UNSAFE_componentWillReceiveProps() {} // Noncompliant
UNSAFE_componentWillUpdate() {} // Noncompliant
}
Instead of componentWillUpdate, use getSnapshotBeforeUpdate together with componentDidUpdate. The
getSnapshotBeforeUpdate lifecycle is called right before mutations are made. The return value for this lifecycle will be passed as the
third parameter to componentDidUpdate.
Instead of componentWillReceiveProps, Use getDerivedStateFromProps together with componentDidUpdate. The
getDerivedStateFromProps lifecycle is invoked after a component is instantiated as well as before it is re-rendered. It can return an
object to update state, or null to indicate that the new props do not require any state updates.
As for componentWillMount, React will call it immediately after the constructor. It only exists for historical reasons and should not
be used. Instead, use one of the alternatives:
state as a class field or set this.state inside the constructor. componentDidMount instead.
class myComponent extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() { // Noncompliant: "componentWillMount" is deprecated
if (localStorage.getItem("token")) {
this.setState({logged_in: true});
}
}
// ...
}
class myComponent extends React.Component {
constructor(props) {
super(props);
if (localStorage.getItem("token")) {
this.setState({logged_in: true});
}
}
// ...
}
UNSAFE_componentWillMount UNSAFE_componentWillReceiveProps UNSAFE_componentWillUpdate