Are there any important difference between state and object in the class?

Multi tool use
Multi tool use


Are there any important difference between state and object in the class?



Let me show what i mean:




class Example extends Component {
constructor(props){
super(props);
this.state = {
prop: 0
}
}
prop = 0;

changeProp = () => {
this.setState({
prop: 5
});
this.prop = 5
}



Both state.prop and prop can used, both can changed, so what's the main difference between them?





Well, if you change this.prop nothing happens besides that change in context of React lifecycle, if you use setState a re-render will be triggered.
– Ramiz Wachtler
Jul 3 at 9:13



this.prop


setState





Change in state will trigger re-render. A component is attached to props and state. So state is something that will make sure you update your component on change
– Rajesh
Jul 3 at 9:13




2 Answers
2



While it is technically possible to alter state by writing to this.state directly, it will not lead to the Component re-rendering with new data, and generally lead to state inconsistency.


this.state


Component



Also, to be remember is that setState is asynchronous. This allows us to have multiple calls to setState in a single scope and not trigger the re-rendering of the whole tree.


setState


allows


setState



States can be modified by this.setState, which will trigger a re-render. But you should not and cannot modify this.props within a Component.


this.setState


this.props



States are used within a component, only the component itself is concerned with its value. However, props are received from its parent, the component only reads from it and renders.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

j,5 o4JtO,ovFG3XaAUWw,eDH Zh8s1XZI7i5IafnX2bHMQyxde7avnkI f
RTpvu5V,8LnJOxF351neRoZBWaRrUHp BwHuw,15BSWlrz6

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications