SIGN IN

React Lesson 3: Exploring the React Component Lifecycle

a stylized React logo

Diving deep into the component lifecycle

To make your code supportable, we need to specify what types of props our component can expect.

Add the following to your comments.js file:

We’re expecting to receive comments from users as evidenced in Line 2 in the code snippet above. In .shape, we define what data type we’re expecting — some examples are text and user, which we’ve used just now.

Let’s add this line to Article.js:

First, you have to install the PropTypes package. Run npm install prop-types: or yarn install prop-types from the project folder.

Then, change your first line to:

Your class will look just like that:

Let’s talk about decorators now. What are they? They are a function which can decorate our component (i.e. fill it with some functionality). In return, this function returns a new component. Let’s write this decorator for comments.

In our case, we’ll finally enrich an old component with some new functionality.

Let’s also import a decorator to CommentList:

We’ll describe our class just the same way as we did before, but we’ll also provide a wrapper around it. Change the last line:

Let’s add State and toggleOpen to the decorator by removing them from the CommentList file. For our component to be aware of those states we describe, we write about states as props in Line 16. Thus, our component will not only contain comments, but also isOpen and toggleOpen. Add a note about it to CommentList:

Remove the lines:

And change the OnClick line as follows:

This approach is far more convenient and clear. This is how your CommentList will look like:

The components that we created are rather simple. Let’s look at the component life cycle in React:

Mounting is the first stage, before the component initialization and its emergence on the DOM tree (this block is marked with a red square on the picture). You can use the constructor to setup initial state for the component. State can be also changed in the getDerivedStateFromProps, but it’s typically reserved to rare cases like animation or data fetch based on props. You can read more about this topic here.

 

(click to open a larger version)

Please notice that this lifecycle was changed since earlier React versions.

Next we do rendering, build a virtual DOM and later, when we’re ready to insert it into a real DOM, we request componentDidMount. Sometimes (just like with CommentList),  our component contains a number of other components: for example, Comment in our case, which has its own Lifecycle methods. So, what would be the proper execution order? First, a parent constructor and getDerivedStateFromProps have to be operational, then render and later, the same methods will be called for the child. After that a render method is over and it starts to get built in a DOM tree. First, componentDidMount of child components finishes its work and only once all child components are ready, a parent componentDidMount will be requested.

Next stage in the component Lifecycle is the update stage, marked with green. It will be executed in three cases: change of the state, change of the props, or call of forceUpdate. Same as in mounting phase, you can use getDerivedStateFromProps if a component state depends on props – it means, you need to control, when they get updated, and change “state” to support its current and updated state.

That’s why you can return new state from getDerivedStateFromProps. It means that the app won’t do rendering more than once. Next render will take place with ComponentDidUpdate (where we’ve already updated). In ComponentDidUpdate, we will have access to both old and new props; while the new ones will be kept in “this,” and the old ones will stay as an argument (prevProps, nextProps). TheshouldComponentUpdate method will be studied in the upcoming lessons.

This scheme works until the component gets fully updated, which will lead to componentWillUnmount – this means that the component is still in DOM but will soon be removed from there. It’s a common situation for clearing some sort of subscriptions.

To understand the working principle of Lifecycle better, let us add the following coding part to class CommentList of our component CommentList:

The work result can be seen in console.

During the Lifecycle stage the component in our DOM tree can be added with new props, and it will be constantly updating. Remember the keys from our previous lessons — we coded the basis for our Articles in those. If we don’t use them, every time our article gets removed for the list, our component will be updated – this means that it won’t get through all Lifecycle stages. But if a key changes, it will force the re-initialization of the whole component. If a key changes, React will remove the previous one and add a new one – it’s extremely convenient if you use third-party libraries like D3 in order to avoid managing all of the components manually.

Sometimes you will need to work with real DOM. React knows this structure – you only need to request it. Use ref. for this purpose. For example, let us add ref to CommentList for an element with Link:

Write the following coding piece in the same file:

Right now we’ve got an access to a real DOM element with Link and can work with it. How can we work with JQuery components? For that purpose, let’s create a file for this JqueryComponent. Write the following:

For example, this kind of construction will be OK for initializing a JQuery plugin. It isn’t the best practice, though, but sometimes it’s necessary in order to avoid too complicated solutions.

Let’s talk about data flows. Sometimes we cannot organize a data flow only in one direction and use a reversed data flow. By default, all data in React gets delivered downwards, but sometimes there can be a need to manage a parent component from a child one. For example, we want to have one article opened at a certain time period and others need to be automatically closed. It means that the information will be kept above, in the parent, and you need to organize a reverse data flow as our components know nothing about each other.

First, we cannot use Functional Component Article List anymore, as we will get a Functional list. Let us start our work on ArticleList coding.

Let’s change import coding in the first line, create class instead of a function, and add “render.” Do not forget to change “import” in the second line. Now let’s create “state” in the fifth line. To do this, we need to know what article is opened; let’s describe it in Line 6. You will also need a method that will be able to open and close your article, so let’s create it in Line 9. In Article we will give the state and function of opening the article – Line 20.

Now you need to change the article by removing unnecessary coding and getting all needed data from props:

Please download the source code here.

Your Home Assignment

You need to create a mixin and decorator for the functionality that we’ve described in this lesson: display of only one opened article, as well as an option of closing all articles and displaying only its titles.

a mockup web page of our blog at blog.soshace.com

See you soon!

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter correct name
Please enter correct email
Looks good!

Related articles

Building a Telegram Bot with Node.js

In this article, you'll learn how to build a Telegram bot using>>>

JavaScript

Handling Side Effects in Redux: Redux-Saga

In this article, we will be covering the handling of side-effects in Redux. This article assumes you have knowledge of React and a bit of>>>

JavaScript
21.11.2019

Why Using Node.js for Developing Web Applications Makes Perfect Sense

Let’s look in more detail at what the inherent benefits of developers using node.js in web applications really>>>

Fundamentals

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy