Bene
Bene

Reputation: 1281

React - setState in componentWillReceiveProps

Is this legal?

componentWillReceiveProps: function(nextProps) {
        if (typeof nextProps.contact != 'undefined') {
            this.setState({forename: nextProps.contact.forename});
            this.setState({surname: nextProps.contact.surname});
            this.setState({phone: nextProps.contact.phone});
            this.setState({email: nextProps.contact.email});
        }
    }

Because I don't know how to fill my inputs and still be able that the user can edit the inputs. So I came up with this solution instead of trying to manipulate the this.props.

Any suggestions?

Upvotes: 35

Views: 40382

Answers (4)

gyosifov
gyosifov

Reputation: 3223

As of React v16.6.3 this is considered UNSAFE and componentWillReceiveProps is marked for deprecation. The removal is planned to happen in version 17.

Note:

Using this lifecycle method often leads to bugs and inconsistencies, and for that reason it is going to be deprecated in the future.

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

For other use cases, follow the recommendations in this blog post about derived state.

If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.

If you used componentWillReceiveProps to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.

In very rare cases, you might want to use the getDerivedStateFromProps lifecycle as a last resort.

In your case you should use componentDidUpdate instead.

Upvotes: 5

Shivam
Shivam

Reputation: 3131

The only reason componentWillReceiveProps exists is to give the component an opportunity to setState. So yes, any state you set synchronously in it will be processed together with the new props.

Upvotes: 0

Haimeng
Haimeng

Reputation: 11

According to this react doc , changing states inside componentWillReceiveProps is not recommended. The doc explains it very clearly.

And it also gives us alternative solutions for "fully controlled component" and "uncontrolled components", please read this react doc

Upvotes: 1

Mikhail Romanov
Mikhail Romanov

Reputation: 1612

Your code is legal according to react documentation.

You also may consider to put this code inside getInitialState method as according to another react doc initializing from props is not an anti-pattern.

You also can replace several calls with one setState method call:

 this.setState({forename: nextProps.contact.forename,
                surname: nextProps.contact.surname,
                phone: nextProps.contact.phone,
                email: nextProps.contact.email});

Upvotes: 39

Related Questions