React Lifecycle Methods

 

Article Image

REACT

INTERVIEW

React Lifecycle Methods

Visual overview of topics covered in this tutorial

Lifecycle

What is the React component lifecycle?

In React, components go through a lifecycle of events:

  • Mounting (adding nodes to the DOM)
  • Updating (altering existing nodes in the DOM)
  • Unmounting (removing nodes from the DOM)

Mounting lifecycle methods

The mounting phase refers to the phase during which a component is created and inserted to the DOM. The following methods are called in order.

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

constructor()

The constructor() is the very first method that is invoked before the component is mounted to the DOM.

The constructor method is called before the component is mounted to the DOM. In most cases, you would initialize state and bind event handlers methods within the constructor method.

Example of the constructor() React lifecycle method in action:

const MyComponent extends React.Component {
  constructor(props) {
   super(props)
    this.state = {
       points: 0
    }
    this.handlePoints = this.handlePoints.bind(this)
    }
}

static getDerivedStateFromProps()

Its main function is to ensure that the state and props are in sync for when it’s required.

The basic structure of the static getDerivedStateFromProps() looks like this:

static getDerivedStateFromProps(props, state) {
  //do stuff here
}
You can return an object to update the state of the component:

static getDerivedStateFromProps(props, state) {
    return {
       points: 200 // update state with this
    }
}

Or you can return null to make no updates:

static getDerivedStateFromProps(props, state) {
 return null
}
class App extends Component {
  state = {
    points: 10
  }

  // *******
  //  NB: Not the recommended way to use this method. Just an example. Unconditionally overriding state here is generally considered a bad idea
  // ********

  static getDerivedStateFromProps(props, state) {
    return {
      points: 1000
    }
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            You've scored {this.state.points} points.
          </p>
        </header>
      </div>
    );
  }
}

The 1000 comes from updating state within the static getDerivedStateFromProps method.

render()

As the name suggests it handles the rendering of your component to the UI

class Hello extends Component{
   render(){
      return <div>Hello {this.props.name}</div>
   }
}

The render() method returns JSX that is displayed in the UI. A render() can also return a null if there is nothing to render for that component.

A render() method has to be pure with no side-effects. React requires that your render() is pure. Pure functions are those that do not have any side-effects and will always return the same output when the same inputs are passed. This means that you can not setState() within a render()You cannot modify the component state within the render().

componentDidMount

After render is called, the component is mounted to the DOM and the componentDidMount method is invoked.

This function is invoked immediately after the component is mounted to the DOM.

You would use the componentDidMount lifecycle method to grab a DOM node from the component tree immediately after it’s mounted.

If you also want to make network requests as soon as the component is mounted to the DOM, this is a perfect place to do so.

componentDidMount() {
  this.fetchListOfTweets() // where fetchListOfTweets initiates a netowrk request to fetch a certain list of tweets.
}

You could also set up subscriptions such as timers

// e.g requestAnimationFrame
componentDidMount() {
    window.requestAnimationFrame(this._updateCountdown);
 }

Updating lifecycle methods

Whenever a change is made to the state or props of a React component, the component is rerendered. In simple terms, the component is updated. This is the updating phase of the React component lifecycle.

  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

shouldComponentUpdate()

In most cases, you’ll want a component to rerender when state or props changes. However, you do have control over this behavior.

Within this lifecycle method, you can return a boolean true or false and control whether the component gets rerendered (e.g., upon a change in state or props).

shouldComponentUpdate(nextProps, nextState)
{
 return this.props.title !== nextProps.title ||
  this.state.input !== nextState.input
}

render()

After the shouldComponentUpdate method is called, render is called immediately afterward, depending on the returned value from shouldComponentUpdate, which defaults to true.

getSnapshotBeforeUpdate()

The getSnapshotBeforeUpdatelifecycle method stores the previous values of the state after the DOM is updated. getSnapshotBeforeUpdate() is called right after the render method.

getSnapshotBeforeUpdate(prevProps, prevState) {

}

Here’s the important thing: the value queried from the DOM in getSnapshotBeforeUpdate refers to the value just before the DOM is updated, even though the render method was previously called.

The getSnapshotBeforeUpdate React lifecycle method doesn’t work on its own. It is meant to be used in conjunction with the componentDidUpdate lifecycle method.

componentDidUpdate()

The componentDidUpdate lifecycle method is invoked after the getSnapshotBeforeUpdate. As with the getSnapshotBeforeUpdate method it receives the previous props and state as arguments:

componentDidUpdate(prevProps, prevState) {

}

However it also takes whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the third argument to the componentDidUpdate method.

componentDidUpdate(prevProps, prevState, snapshot) {

}

Unmounting lifecycle method

The following method is invoked during the component unmounting phase

  • componentWillUnmount()

componentWillUnmount()

The componentWillUnmount lifecycle method is invoked immediately before a component is unmounted and destroyed. This is the ideal place to perform any necessary cleanup such as clearing up timers, cancelling network requests, or cleaning up any subscriptions that were created in componentDidMount().

// e.g add event listener
componentDidMount() {
  el.addEventListener()
}
// e.g remove event listener
componentWillUnmount() {
  el.removeEventListener()
}

References:

Thanks for reading!!!

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...