Article

Lifecycle Methods in React: A Gist

Published: 20 Dec 2021 | Last updated 20 December 2021

Let's discuss some of them:

  componentDidMount() {
   // Get the data I need to correctly display
 }

 The very first time the component shows up, React calls the componentDidMount method. Most common use case is to make an API call to get some data to correctly display.

 componentWillReceiveProps(nextProps) {
   if (nextProps.whatever !== this.props.whatever) {
     // do something important here
   }
 }

Called when the component is receiving props from say Parent component. It runs every time a Parent component decides to hand props to the child component.

 Note: **componentWillReceiveProps** lifecycle method has been deprecated and will be removed in the version 17 of React


 shouldComponentUpdate(nextProps, nextState) {
   // return true if want it to update
   // return false if not
 }

This can be used to optimize our app


componentWillUnmount() {
   // teardown or cleanup our code before the component disappears
   // eg. remove event listener
 }


One more important Lifecycle method:

componentDidUpdate(prevProps, prevState) {}

This methods runs every time the component gets re-rendered post the first render

 **NOTE:** whenever calling **setState** inside **componentDidUpdate** be very cautious as it can end up with an infinite loop. This is because setting state leads up to re-rendering of component which will also invoke **componentDidUpdate** method

Methods that have been deprecated are:

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

New Lifecycle methods:

static getDerivedStateFromProps(props, state) {
   // return the new, updated state based upon the props
}

To read more about it here's a link:

  • https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
  • Here's an article why we probably don't need this method much:
  • https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
getSnapshotBeforeUpdate() {
   // create a backup of the current way things are
}

To read about it:

  • https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate

To learn more about it, here are some reads:

  • https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1
  • https://reactjs.org/blog/2018/03/29/react-v-16-3.html#component-lifecycle-changes
  • Techtud Admin
  • @techtud
  • Senior editor at techtud

What to read next

Sounds rather exhausting, right?Well, it was indeed exhausting! Many of the times but when I analyze what all I was able to accomplish in a year's

Here is a time worthy documentation: