Chapter 6. The React Component Lifecycle

The goal of this chapter is for you to learn about the lifecycle of React components and how to write code that responds to lifecycle events. We'll kick things off with a brief discussion on why components need a lifecycle in the first place. Then, you'll implement several example components that initialize their properties and state using these methods.

Next, you'll learn about how to optimize the rendering efficiency of your components by avoiding rendering when it isn't necessary. Finally, you'll see how to encapsulate imperative code in React components and how to clean up when components are unmounted.

Why components need a lifecycle

React components go through a lifecycle, whether our code knows about it or not. In fact, the render() method that you've implemented in your components so far in this book, is actually a lifecycle method. Rendering is just one lifecycle event in a React component.

For example, there's lifecycle events for when the component is about to be mounted into the DOM, for after the component has been mounted to the DOM, when the component is updated, and so on. Lifecycle events are yet another moving part, so you'll want to keep them to a minimum. As you'll learn in this chapter, some components do need to respond to lifecycle events to perform initialization, render heuristics, or clean up after the component when it's unmounted from the DOM.

The following diagram gives you an idea of how a component flows through its lifecycle, calling the corresponding methods in turn:

Why components need a lifecycle

These are the two main lifecycle flows of a React component. The first happens when the component is initially rendered. The second happens whenever the component is re-rendered. However, the componentWillReceiveProps() method is only called when the component's properties are updated. This means that if the component is re-rendered because of a call to setState(), this lifecycle method isn't called, and the flow starts with shouldComponentUpdate() instead.

The other lifecycle method that isn't included in this diagram is componentWillUnmount(). This is the only lifecycle method that's called when a component is about to be removed. We'll see an example of how to use this method at the end of the chapter. On that note, let's get coding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.150.59