React Lifecycle Methods

Zoe Bai
5 min readMay 6, 2019

In our materials, there is a section called Lifecycle Methods that we, so far, haven’t really used much or discussed much about. I first noticed it soon after this Mod in a review lecture where we used it to fetch data instead of how we did it before in JavaScript. Soon later, I found the answer in the newly released labs.

It feels overwhelming in the first as there are so many of them, but they actually fire in order and we don’t necessarily need all of them. The graph below describes when they they fire in a whole React lifecycle:

There are three phases in total: mounting phase, updating phase and unmounting phase.

Mounting Phase

This is when the component is first created and mount the DOM. Here we can create constructor. But as we already know, this is unnecessary. We generally don’t need to do anything with the constructor, instead, we will have our initial state (if your component is a “container component”) to store properties and change them later to your need. The component will mount only once until we refresh the page.

Then we have #static getDerivedStateFromProps. This one is not used much. It exists for only one purpose: It enables a component to update its internal state as a result of changes in our props. We receive the props from the parent as well as the current state of this component, and we compare the props received to the current state, then return a new state object if we want or return null if there no changes.This method will fire in every render.

class List extends React.Component {   
static getDerivedStateFromProps(props, state) {
if (props.selected !== state.selected) {
return { selected: props.selected, };
}
// Return null if the state hasn't changed
return null;
}
// ... }

After this is our #render, where the main code meat resides. This is required in every component as it decides what JSX code to display on the browser. An important thing here is to remember to always wrap your content in one single element.

The last one in mounting phase is #componentDidMount. This method, different from the last few, will be needed in a lot of cases. It is called by React itself. This method is only rendered once when the component mounted. Scenarios of using this method would be fetch(get) data, and set our state with the received data, or setInterval / setTimeout for an event.

Updating Phase

When in update phase, we will again meet this #static getDerivedStateFromProps. This will triggers when either the state updates or props receive change.

Then we have #shouldComponentUpdate. The return value of it is Boolean. It receives the next props and the next state. We can compare the old props with the new props, and the current state with the new state. We can return faulty if we want to prevent the component from updating and re-rendering, otherwise we can just return true. Alternatively, we can use “pure component”, which also compares old and new props and states, but it doesn’t have access to this #shouldComponentUpdate.

After this, we just render the content, and we will get to the next step #getSnapshotBeforeUpdate. What it does is to grab the value (previous pros and states)right before we update. We can think of using Github — we would add, stage to commit the changes and then push the changes. Stage to commit is exact the same idea as this lifecycle method. Although we might barely need, it is good to know that for any app that is based on scroll position, this method can come in handy.

src: The (new) React lifecycle methods in plain, approachable language
src: The (new) React lifecycle methods in plain, approachable language

The final step of this phase is #componentDidUpdate. This is called after the actual template is rendered in the DOM. Similar to #getSnapshotBeforeUpdate, this method also receives two arguments — prevState and preProps. Bear in mind that if you want to set the state here, you have to wrap them up in a condition to change the state only when the previous values and the current values are different. Otherwise you will fall into an infinite loop as it renders every time the state changes.

// BAD EXAMPLE
componentDidUpdate(prevProps, prevState) {

let height = ReactDOM.findDOMNode(this).offsetHeight;
this.setState({ internalHeight: height });
}

// correct
componentDidUpdate(prevProps, prevState) {
let height = ReactDOM.findDOMNode(this).offsetHeight;
if (this.state.height !== height ) {
this.setState({ internalHeight: height });
}
}

Unmounting Phase

At the end of the React lifecycle, there is #componentWillUnmount. The purpose of this method is to delete whatever we setup in the # componentDidMount from the first phase. For example, we fire a timer component that updates the time every second by #setInterval. The user is allowed to remove this timer if they want. When the timer gets removed, it should trigger the #componentsWillUnmount to clear out that #setInterval in order to keep our app light and clean. If we leave them there, we may run into trouble once the app scales up.

 class Timer extends React.Component {
state = {
date = new Date()
}
//setup timer
componentDidMount = () => {
this.timerHandle = setInterval(()=>{
this.setState({date:new Date()}),
1000})
}
//clear timer
componentWillUnmount = () =>{
if(this.timerHandle){
clearInterval(this.timerHandle)
}
}
}

Conclusions

What we need to use the most is probably #componentDidMount, as we want the users to see something when they first render a web page. If we have an app that needs to constantly compare the old props and states with the new props and states, we might need #getSnapshotBeforeUpdate. Also after we finish our interaction with the page, and want to clear out some functions we setup in the beginning, it is good to use #componentWillUnmount. Use them selectively to achieve your goals!

References

  1. https://www.youtube.com/watch?v=iYz2OKWO09U&list=PL4cUxeGkcC9ij8CfkAY2RAGb-tmkNwQHG&index=23&t=0s
  2. http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
  3. https://programmingwithmosh.com/javascript/react-lifecycle-methods/
  4. https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
  5. https://www.codingame.com/playgrounds/8747/react-lifecycle-methods-render-and-componentdidmount
  6. https://blog.logrocket.com/the-new-react-lifecycle-methods-in-plain-approachable-language-61a2105859f3
  7. https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.html
  8. https://alligator.io/react/get-derived-state/

--

--