5️⃣

3.5 State and Life-cycle Methods

Review of States

To understand lifecycle methods, we will need to utilize states. As a quick refresher, a state in React is an object which represents data that can change throughout the lifecycle of a component. When the state of a component is modified, the component is re-rendered. To update the state, the setState() method is used, which merges the new state with the previous state.
Instead of directly assigning values to a component, we can use setState() for example as in:
notion image
We can also update the state asynchronously using a callback function. This function receives two parameters: state and props. Inside the function, we can create a new state object and update it by adding the value of props.increment to the current state.counter.
notion image
The following example uses a UserInfo component that displays the user's name. Inside the updateUserInfo method, we use setState() to update the age property of the user object by incrementing it by 1 and merging it with the previous state. When the updateUserInfo method is called, the setState() method is triggered and we update the age property accordingly.
notion image
notion image

Lifecycles in React

In React, each component has a lifecycle. This refers to the stages that a component goes through, from its creation to its removal from the DOM. It starts at their initialization, the mounting, continues through their updates, the growth, and ends at their removal, the demounting.
Lets say, in our previous example, each user ages every minute. We want to set up their age counter when their user is rendered to the DOM for the first time (also known as mounting). We will clear that timer when the user is removed from the dom (also known as unmounting, or demounting).
We start with creating the user and a place to store the timer ID:
notion image
The componentDidMount() method runs after the component output has been rendered to the DOM, hence it is when the timer on the user's age begins.
notion image
When the component unmounts, we remove the timer via the componentWillUnmount() lifecycle method.
notion image
Finally, we render the user and their age:
notion image
Together, this looks like:
notion image
notion image
notion image

Previous Section

Next Section

Add a page link block here (if there is no next section, delete this column)
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.