For working with any tech you must know the lifecycle. When writing React components, we need access to lifecycle events to handle a variety of side effects: like fetching data on mount, changing props when the component updates, cleaning up before the component unmounts, etc.


React Lifecycle Method Explained

First, let’s take a look at how it’s been done traditionally. As you probably know, each React component has a life cycle, which consists of three phases:

  • Mounting, that is putting inserting elements into the DOM.
  • Updating, which involves methods for updating components in the DOM.
  • Unmounting, that is removing a component from the DOM.

Image for post

Image provided by the author.

Each phase has its own methods, which make it easier to perform typical operations on the components. With class-based components, React developers directly extend from the React.Component in order to access the methods.

Until React 16.8, the most common solution for handling lifecycle events required ES6 class-based components. In other words, if our code was already written using functional React components, then we first would have to rewrite those components as classes that extend React.Component with a dedicated render function. Only then would it be possible to access the three most common lifecycle methods: componentDidMountcomponentDidUpdate, and componentWillUnmount. (For the purposes of this article, we will only cover these three lifecycle methods. Since other lifecycle methods will be deprecated in React 17, and, in the interim, require the use of the UNSAFE_ prefix, we will not cover them in this post.) The following diagram illustrates when these methods are invoked in the context of the component lifecycle:

Image for post

#javascript #react-hook #react #nodejs #programming

React Component Lifecycle Methods With React Hooks
1.30 GEEK