React lifecycle methods: Understandings and how to implement them without messing up

As we know, everything in this world follows a cycle (say humans or trees). We are born, grow, and then die. Almost everything follows this cycle in its life, and React components do as well. Components are created (mounted on the DOM), grow by updating, and then die (unmount on DOM). This is referred to as react lifecycle methods. This not only can help compartmentalize our app, but we can also customize each compartment.

Through lifecycle methods, we can then control what happens when each tiny section of your UI renders, updates, thinks about re-rendering, and then disappears entirely. These methods give us better control over our component and we can manipulate them. So now, in this article, we – ArrowHiTech would like to introduce to you guys the definitive knowledge of react lifecycle methods, as well as how to implement them without messing up.
Let’s get into it!

What are React lifecycle methods?

You can think of React lifecycle methods as the series of events that happen from the birth of a React component to its death. Every component in React should go through this lifecycle of events. Through lifecycle methods, we can then control what happens when each tiny section of your UI renders, updates, thinks about re-rendering, and then disappears entirely.

  • Mounting – Birth of your Component
  • Updating – Growing of your component
  • Unmounting – Death of your component

The React lifecycle methods diagram

The diagram below is from the official React documentation showcasing the different React lifecycle methods and when they are invoked.

Some common React lifecycle methods (and how to implement them)

#1. render()

This is one of the most widely used React lifecycle methods, as it is the only required method. What it does is it is handling the rendering of your component as its name says while inspecting this.sate and this.props. Because the name suggests it handles the rendering of your component to the UI. It happens during the mounting and updating of your component. Below, we also would like to give an example of this method:

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

As you can see in the example above, the render() method returns JSX that is in the UI. A render() can also return a null if there is nothing to render for that component. Furthermore, keeping your render() simple and clean without state updates makes your app maintainable.

#2. constructor()

The constructor for a React component is called before it is mounted. When implementing the constructor for a React component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs. These React lifecycle methods are for two purposes: initializing the state and binding method to the component.

This is an example of a constructor method in React.

 constructor(props) {
    super(props);
    // Don't call this.setState() here!
    this.state = { counter: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

#3. componentDidMount()

The thing about componentWillMount is that there is no component to play with yet, so you can’t do anything involving the DOM. Also, nothing has changed since your component’s constructor was called, which is where you should be setting up your component’s default configuration anyway. You can modify these react lifecycle methods state within the componentDidMount(), but use it with caution.

componentDidMount()

It is recommended that you use this with caution since it could lead to performance issues. The best practice is to ensure that your states are assigned in the constructor(). The reason React allows the setState() within this lifecycle method is for special cases like tooltips, modals, and similar concepts when you would need to measure a DOM node before rendering something that depends on its position.

#4. componentDidUpdate()

This is one of the React lifecycle methods that can invoke as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes. You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from the previous state. Incorrect usage of setState() can lead to an infinite loop.

Take a look at the example below that shows a typical usage example of this lifecycle method.

 componentDidUpdate(prevProps) {
  //Typical usage, don't forget to compare the props
  if (this.props.userName !== prevProps.userName) {
    this.fetchData(this.props.userName);
  }
 }

#5. componentWillUnmount()

As the name suggests this lifecycle method is called just before the component is unmounted and destroyed. If there are any cleanup actions that you would need to do, this would be the right spot. You cannot modify the component state in componentWillUnmount() lifecycle. This component will never be re-rendered and because of that, we cannot call setState() during these react lifecycle methods. Here is an example of this method:

 componentWillUnmount() {
 window.removeEventListener('resize', this.resizeListener)
}

Common cleanup activities performed in this method include clearing timers, canceling API calls, or clearing any caches in storage. Moreover, You should not call setState() in componentWillUnmount() because the component will never be re-rendered.

Final words

That may conclude all the knowledge you need to know about the common React lifecycle methods, and also, how to implement them without messing things up. If you are new to React, that certainly covers all the key topics that you will need to learn to be proficient with the React lifecycle. Use these methods sparingly, and use them with care. We hope this article has been helpful in illuminating when and how to use lifecycle methods.

We – ArrowHiTech is proud to be one of the most well-established outsourcing companies all around the world. That is to say, with over 12 years of experience, we can provide the best mobile app development services for your business. Also, if you want to go through our showcase, you should visit our product page here: MageSolution or our portfolio: ArrowHiTech portfolio.

ArrowHiTech services

If you have any questions, don’t hesitate to contact us via email support@arrowhitech.com or our phone number +84 243 7955 813. We would love to hear every feedback from you guys.

Related News

Redux: Reasons to use and how to use it in ReactJs

Nativescript Vs. React native for for JavaScript mobile development

Tags

Share