The state object is where you store property values that belong to the component. When the state object changes, the component re-renders.
Each component in React has a lifecycle which you can monitor and manipulate during its three main phases: Mounting, Updating, and Unmounting.
Coming to the State,it contains data specific to a component which might change over time.The state is user-defined , and it should be a plain JS Object.
Using State Correctly :
- Do not modify state directly
- State updates may be asynchronous
setState() is an asynchronous function, so if you want to view/assign the updated value,you should do that inside a callback function to be sure that the updated value of the state is used.
When a component is rendered to the DOM for the first time, it is known as mounting.
AND when the DOM produced by the component is removed,it is called unmounting.
We can declare special methods, called lifecycle methods,on component Class to run some code when a component mounts and unmounts.
In this example, when the compenent color is rendered, the componentDidMount() method fires and changes the state after 3 sec.
Similarly,the componentWillUnmount() method is called just before the component is removed from the DOM.
Thanks for Reading !