fs2005
fs2005

Reputation: 591

Constructor vs componentWillMount

In ReactJs, what can we do using componentWillMount that we cannot do via the constructor? Both are called once and before the component is rendered.

import React from 'react';

class Display extends React.Component {
  constructor(props)
  {
    super(props)   
    console.log('Display.Constructor...')
    console.log(this.props)
  
  }


  componentWillMount(){
    console.log('Display.componentWillMount...')
    console.log(this.props)
  }

Upvotes: 4

Views: 2168

Answers (1)

rodcunha
rodcunha

Reputation: 431

I believe that from React 17, ComponentWillMount will have to be prefixed with UNSAFE_ in order to be used and its use is discouraged.

I think the only thing you can't achieve inside the constructor that you can with ComponentWillMount is to setState() also react throws a warning if anything inside your constructor modifies state even in another component.

There is a thread here that may be of interest to you on this topic.

Upvotes: 2

Related Questions