DEV Community

Cover image for State & Lifecycle
Aditya Sharan
Aditya Sharan

Posted on

State & Lifecycle

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.

--

Here's example showing how to use state :
Alt Text

Using State Correctly :

  • Do not modify state directly

Alt Text

the only place you can directly assign this.state is the constructor.
  • State updates may be asynchronous

Alt Text

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.


The componentDidMount() method runs after the component has been rendered to the DOM :
Alt Text

In this example, when the compenent color is rendered, the componentDidMount() method fires and changes the state after 3 sec.
The output changes from "Favourite color is red " to "Favourite color is yellow".

Similarly,the componentWillUnmount() method is called just before the component is removed from the DOM.
Thanks for Reading !

Top comments (0)