I have seen both
export default class LoginScreen extends React.Component {
constructor(props){
super(props);
this.state = {
loading: false,
loggedIn: false,
}
}
}
and
export default class LoginScreen extends React.Component {
state = {
loading: false,
loggedIn: false,
}
}
What are the use cases for both? Are there advantages / disadvantages? Is one a better practice?
The constructor and getInitialState both in React are used to initialize state, but they can't be used interchangeably. The difference between these two is we should initialize state in the constructor when we are using ES6 classes and define the getInitialState method when we are using React. createClass (ES5 syntax).
constructor() Typically, in React constructors are only used for two purposes: Initializing local state by assigning an object to this.state . Binding event handler methods to an instance.
You can also use state in React function components (without a constructor), but using higher-order components or render prop components.
Don't “copy props into state.” It creates a second source of truth for your data, which usually leads to bugs. One source of truth is best. Components will already re-render when their props change, so there's no need to duplicate the props as state and then try to keep it up to date.
Use constructor when you want to save props
data into state
export default class LoginScreen extends React.Component {
constructor(props){
super(props);
this.state = {
loading: props.loading,
loggedIn: props.loggedIn,
}
}
}
Otherwise you can directly set the state
for hard coded data
export default class LoginScreen extends React.Component {
state = {
loading: false,
loggedIn: false,
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With