Naeem Naeem - 1 month ago 21
React JSX Question

what is the difference between getDefaultProps and getInitialState react js

I am new in react js.

getDefaultProps () {
return {
backgroundColor: 'gray',
height: 200,
width: 200
}
},


I've same values for
getDefaultProps
and for
getInitialState
:

getInitialState () {
return {
backgroundColor: 'gray',
height: 200,
width: 200
}
},


What is the logical difference in between both. which should supposed to override or which one will execute first.

Thanks.

Answer

getInitialState

  • The object getInitialState() Invoked once before the component is mounted. The return value will be used as the initial value of this.state.

Note: This method is not available on ES6 class components that extend React.Component. For more information, please read our documentation about ES6 classes.

getDefaultProps

  • The object getDefaultProps() Invoked once and cached when the class is created. Values in the mapping will be set on this.props if that prop is not specified by the parent component (i.e. using an in check).
  • This method is invoked before any instances are created and thus cannot rely on this.props. In addition, be aware that any complex objects returned by getDefaultProps() will be shared across instances, not copied.
Comments