DEV Community

Cover image for State & Lifecycle
Aditya Sharan
Aditya Sharan

Posted on

3 2

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 !

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay