Why components need a lifecycle

React components go through a lifecycle. 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 are lifecycle events for when the component is 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, clean up after the component when it's unmounted from the DOM, or to handle errors thrown by the component.

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

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 updated. Here's a rough overview of each of the methods:

  • getDerivedStateFromProps(): This method allows you to update the state of the component based on property values of the component. This method is called when the component is initially rendered and when it receives new property values.
  • render(): Returns the content to be rendered by the component. This is called when the component is first mounted to the DOM, when it receives new property values, and when setState() is called.
  • componentDidMount(): This is called after the component is mounted to the DOM. This is where you can perform component initialization work, such as fetching data.
  • shouldComponentUpdate(): You can use this method to compare new state or props with current state or props. Then, you can return false if there's no need to re-render the component. This method is used to to make your components more efficient.
  • getSnapshotBeforeUpdate(): This method lets you perform operations directly on DOM elements of your component before they're actually committed to the DOM. The difference between this method and render() is that getSnapshotBeforeUpdate() isn't asynchronous. With render(), there's a good chance that the DOM structure could change between when it's called and when the changes are actually made in the DOM.
  • componentDidUpdate(): This is called when the component is updated. It's rare that you'll have to use this method.

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
3.138.204.208