DEV Community

mcwachira
mcwachira

Posted on

Day 5 of the #100daysofCode Challenge. Learning React React Lifecycle Methods

Its Day 5 of the #100daysofCode challenge and we are going to talk about react lifecycle methods.

React Lifecycle Methods

So the first question that comes to mind is what are React lifecycle methods?
You can think of lifecycle methods as series of events that happen sequentially from the conception and birth of a react component to its death.
There are three main stages in a react component lifecycle where the component ia monitored and manipulated.
The three main stages include
1.Mounting - conception and birth of a react component
2.updating - growth of a react component
3.unmounting - death of a react component

Mounting

This is the stage where elements are placed in the dom.
There are four built in methods in this stage

  • Constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

out off the four the most commonly methods are

1.constructor()

The constructor() method is called before the component is initialized and its where the initial state is placed
The method is called with props as arguments

class Counter extends React.Component {
  constructor(props) {
    super(props);
      count: 0,
    };
  }

Enter fullscreen mode Exit fullscreen mode

In the above example we have created a simple counter component and placing its initial state in the constructor method and setting its initial value to zero.

2.render()

This is the only required method in a component and its role is to handle the rendering of your component to the UI.

class Person extends React.Component{
render(){
 return    <div> my name is charles and am 27 years old</div>      
      }
}
Enter fullscreen mode Exit fullscreen mode

The above example shows the render() method returning jsx which is displayed on the ui.

3.componentDidMount()

This method comes into play after your component has been mounted.Its called once in the lifecyle process and it signifies that you component has been rendered properly.
Its at this point where data from a remote api can be brought in.
Here we can use the setSate() method to update the state.This will cause a re-render to occur but it will happen before the browser updates the ui.

componentDidMount() {
   const json = localStorage.getItem("count");
   const count = JSON.parse(json);
   this.setState(() => ({ count: count }));
    }
  }
Enter fullscreen mode Exit fullscreen mode

In the above simple example data is fetched from local storage and it used to update the state via the setState method.

Updating

Its the next stage in the lifecycle process and its during this stage that the component is updated.
It consist of five built in methods which are called in order when the component is updated

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

In the update stage the the most common method is

componentDidUpdate()

Its called after the component has been updated in the dom and any rendered html has finished loading.
It takes in two arguments props and state which updates the dom as soon as changes occur in either.
The setState() can be called in this method but it must be wrapped in a conditional statement in order to check for changes in state or props.
Wrapping it in conditional statement will prevent it from from forming an infinite loop.

 componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) {
      const json = JSON.stringify(this.state.count);
      localStorage.setItem("count", json);
    }

Enter fullscreen mode Exit fullscreen mode

In the above code example we taking in our previous prop and state and checking if the previous state count is similar to the current state count and if its not we then store the current state count in local storage.

Unmounting

This is the next phase of the lifecycle where the component is removed from the dom.
It consist of only one method

  • componentWillUnmount()

componentWillUnmount()

Its called write before the component is removed from the dom.
In this method you can perform the necessary clean ups like invalidating timers, canceling network requests, removing event listeners or canceling any subscriptions made in componentDidMount().

componentWillUnmount() {
  clearInterval(this.interval);
}

Enter fullscreen mode Exit fullscreen mode

REACT COMPONENT LIFECYCLE DIAGRAM

The diagram below gives an overview of the different react lifecycle methods. Its from the official react documentation

download (4).jpeg

This has been my firth day learning react and is has been awesome and interesting.
cheers guys and happy learning.
Connect with me on twitter and lets talk about react

Top comments (0)