It’s Alive! React Component Lifecycle

Wendy Raven McNair
2 min readApr 7, 2021

--

Image by sethJreid from Pixabay

I’d like to go more in depth on something I briefly touched on in my previous blog (React Technical Interview) and that’s the lifecycle of a React component. The definition of lifecycle in Webster’s dictionary is:

“a series of stages through which something (such as an individual, culture, or manufactured product) passes during its lifetime”

So the lifecycle of a React component can be described as the different stages through which a component passes during its existence.

The component lifecycle consists mainly of three stages; mounting (creation), updating, and unmounting (deletion). A lifecycle diagram cheat sheet is provided for reference at this link https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram.

This lifecycle structure allows for built-in events called lifecycle hooks or lifecycle methods. Programmers can override these methods and code desired behaviors into an app. Let’s cover a few of the methods that arise during a component’s lifecycle. They are invoked or called in the order they’re listed below.

CONSTRUCTOR

Programmers can implement the constructor to initialize state or bind methods. It’s called before it’s mounted which provides an opportunity to set the initial state of a component. This can be used to capture a user’s input on a form that once submitted can be stored in a list for the user to reference at a later date (ex. todo list, vocabulary words list, etc).

Note, do not call setState in the constructor. The constructor is the only place to set initial state by assigning this.state directly. In all other methods, use this.setState.

COMPONENT DID MOUNT

The componentDidMount method is invoked immediately after a component is mounted (created and inserted onto the DOM tree). Programmers can load data from a remote endpoint (backend database) for use in an app. This can be used to display browser views when a user visits a website.

COMPONENT DID UPDATE

The componentDidUpdate method is called immediately after an update happens. Programmers use this to change the DOM when the component has been updated. This can be used to show different browser views as a user clicks for various information on a website.

COMPONENT WILL UNMOUNT

The componentWillUnmount method is invoked right before a component is unmounted and destroyed. Once a component instance is unmounted, it will never be mounted again. Programmers use this method to perform “cleanup” such as canceling network requests or removing any timers that were defined.

There are several other lifecycle methods programmers can use but the ones listed above are the most commonly used. Details on all lifecycle methods are located at this link https://reactjs.org/docs/react-component.html.

--

--

No responses yet