Suppose, you don't have a girlfriend or boyfriend. So you don't have any opportunity to send a love letter. In this situation, you can create a love letter for yourself and modify it later. When you modify your own love letter that is written for yourself, it will not affect anything. Now we can start with the state object. state is a built-in object in React. It allows the component to create and manage their own data same as your love letter for yourself. The state doesn't allow passing data from one component to another. Why do you need to pass your love letter when you are single? - You can manage and create data internally. Let's build a counter using state.
import React from 'react'
class Test extends React.Component {
constructor(props){
super(props)
this.state = {
count:0
}
}
increment(){
this.setState({
count:this.state.count+1
})
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={()=>{this.increment()}}>increment</button>
</div>
);
}
}
export default Test ;
when you click the increment button, the state will increase.
btw change on state happens based on user input. when React gets informed about the change it immediately re-render the DOM. But it's re-render only responsible components with the updated value. It makes react faster. Once upon a time state was only used for class components. But after introducing React Hooks state can be used in class and functional components.
Top comments (0)