I've seen some react developers define state without a constructor. I like the fact that is simplifies the code, but is it safe to do so?
class Dog extends React.Component {
state = { sound: 'Woof' }
return (
<p>Dog says { this.state.sound }</p>
)
}
I apologize in advance for the over simplified example.
React State without a Constructor In React, state is used in a React class component. There you can set initial state in the constructor of the class, but also access and update it with this.state and this.setState, because you have access to the class instance by using the this object. import React, { Component } from 'react';
You have learned, that there is no constructor needed to set the initial state of a React component by using class field declarations in enviroments where these are supported. Moreover, you have experienced how higher-order components or render prop components can be used to make a functional component stateful.
In React, state is used in a React class component. There you can set initial state in the constructor of the class, but also access and update it with this.state and this.setState, because you have access to the class instance by using the this object. import React, { Component } from 'react'; const list = ['a', 'b', 'c'];
The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.
Its exactly the same thing. Take a look at the javascript that babel transpiles the code into. There is no difference.
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