Lifecycle of React Native Components

We are familiar with the word “lifecycle”. In human life, the lifecycle has three phases -

  • birth
  • life
  • death

In react native its component lifecycle is almost the same as the human lifecycle. The life cycle of the react-native component starts when it is created. We can manipulate and monitor components during their life cycle.

Life cycles of react-native components :

Lifecycle Of React Native Components
  1. Mounting
  2. Updating
  3. Unmounting
  4. Error handling.

Mounting :

The birth of the component is known as mounting. In this phase, elements are put into the DOM.

Methods that are called during mounting any element  -

  1. constructor
  2. getDerivedFromProps
  3. Render
  4. componentDidMount

Constructor :

If you are familiar with OOPs(Object Oriented programming ) you must have heard word constructor. in react- native we use the constructor to initialize objects.

Objects are the same as react-native states. it is also used to bind event handler methods of react-native. For example, if you are in a child component and want to access functions of the parent component then we will be using a constructor.

So constructor has the following applications  :

  1. Initializing objects/states.
  2. Binding methods.

Note: Constructors can be used only in a class component, not in functional components.

getDerivedFromProps:

It is called just before calling the render method. It takes two arguments - props and states. it returns an object if something has changed and null if nothing has changed. it is very rarely used because of the availability of simpler alternatives

Render: it is a very important method. It does not interact with the browser directly.it returns the same result each time whenever invoked.

componentDidMount:

When in DOM(Document Object Model) all the child elements and components are mounted, this method is called.it is the last phase of the mounting phase. componentDidMount works bottom to top but all other methods work top to bottom. Working bottom to the top ensures that all child components are mounted and all native components can be accessed.

Updating: if there is a change in props or state then it's called that component is updated.

above methods are called in the order below -

  1. getDerivedStatesFromProps
  2. shouldCompontUpdate
  3. Render
  4. getSnapshotBeforeUpdate
  5. componentDidUpdate

getDerivedFromProps: It is called just before calling the render method. props and states are taken as an argument. it returns an object if something has changed and null if nothing has changed. simpler alternatives of getDerivedFromProps are available which is why it is rarely used.

 shouldComponentUpdate: it is executed when there is a change in props and state of any component. Through this, we can even restrict the update of any component. it always returns a boolean value. If it is false then no update is allowed or reflected but if it's true then an update is allowed and reflected.

Render: it is one of the important methods. Render does not interact with the browser directly. It returns the same result each time whenever invoked.

getSnapshotBeforeUpdate : it executed after render. it captures information from DOM(Document Object Model) about component before it is changed.it takes previous props(prevProps) and previous state(pevState) as an argument.

componentDidUpdate : it works just after getSnapshotBeforeUpdate. It performs some operations after the update of DOM. it's called only if a component or state is changed.

 Unmounting: removal of components is called unmounting.

The method that is called while unmounting :

  1. ComponentWillUnmount

ComponentWillUnmount : whenever the component is removed it is immediately called. The component will never be re-rendered after unmounting. it invalidated timers, cancel requests and removes subscription, and performs every other necessary cleanup.

Error handling:  This deals with exceptional cases. Whenever an error is encountered in any phase (rendering,getSnapshotBeforeUpdate,componentDidUpdate calling constructor, etc) well in that case Error handling is responsible for proper execution.

All of us know that dealing with errors is the crucial part and we should be proficient in this.

We use these methods for error handling :

  1. getDerivedStateFromError
  2. componentDidCatch

getDerivedStateFromError: whenever an error is thrown in a component this method is called and the error is passed as an argument and whatever the method returns are used to update the component. It is called during rendering.

componentDidCatch: It only works for catching errors thrown by the component’s children. It is called during the commit phase. It takes two parameters as an argument and that is error and info.

Example of the react-native life cycle :

I hope from the above explanation you have gained a basic idea about the lifecycle of react components and their methods. so now we will be implementing it practically.

App.js code:

import React from 'react';
import {View,Text} from 'react-native';
class App extends React.Component{
  constructor(){
    super();
    this.state={color:'red'}
    console.warn('constructor');
  }
  static getDerivedstateFromprops(){
console.warn('getDerivedstateFromprops');
return {};
}


render(){
  console.warn('render',this.state.color);
  return(<View><Text>Test {this.state.color}</Text></View>);
}


}
export default App;

Note: Run your app using the web for proper inspection

Explanation:  we know about constructors but you may think that why are we using “super()”?

So super() basically calls the parent class constructor. we have initialized the color as red.

If you will execute the above code you will find it is showing - “Test red” on the output screen.

Let's open the console -

Right-click on the mouse, then you will see a menu has opened then click on inspect. After clicking on inspect you will see a console option there, click on that, and then you can see the sequence of execution there.

Firstly it is constructor then render, same as the picture below -

Lifecycle Of React Native Components

Now we will be calling componentDidMount.

Firstly let's look at the code.

App.js code With componentDidMount :

import React from 'react';
import {View,Text} from 'react-native';
class App extends React.Component{
  constructor(){
    super();
    this.state={color:'red'}
    console.warn('constructor');
  }
  static getDerivedstateFromprops(){
console.warn('getDerivedstateFromprops');
return {};
}
componentDidMount(){
  this.setState({color:'green'});
  console.warn('componentdidmount');
  return {};
}
render(){
  console.warn('render',this.state.color);
  return(<View><Text>Test {this.state.color}</Text></View>);
}


}
export default App;

Explanation :

Firstly let's recall what componentDidMount does  -

componentDidMount : When in DOM(Document Object Model) all the child elements and components are mounted, this method is called.it is the last phase of the mounting phase. componentDidMount works bottom to top but all other methods work top to bottom. Working bottom to the top ensures that all child components are mounted and all native components can be accessed.

So it simply means that if we will execute the code above render will be updated and the output screen will be displaying “Test green”.

Lifecycle Of React Native Components

So we can see firstly the render was returning as “red” and as we called “componentDidMount “ it is recalled and we can see “green” instead of “red”.

Updating :

import React from 'react';
import {View,Text} from 'react-native';
class App extends React.Component{
  constructor(){
    super();
    this.state={color:'red'}
    console.warn('constructor');
  }
  static getDerivedstateFromprops(){
console.warn('getDerivedstateFromprops');
return {};
}
componentDidMount(){
  this.setState({color:'green'});
  console.warn('componentdidmount');
  return {};
}
componentDidUpdate(){
  console.warn("componentDidUpdate");
  }
render(){
  console.warn('render',this.state.color);
  return(<View><Text>Test {this.state.color}</Text></View>);
}


}
export default App;

Output  :

Lifecycle Of React Native Components

So we see the sequence of execution. we have learned about many other methods under mounting, updating, unmounting and error handling and those will work as same as their sequence.

It was a class component life cycle. Let’s look at what happens in the functional component -

Functional components: Functional components do not use lifecycle methods, they are called stateless components as they do not control their own state. It is simply a plain javascript function. we know how important is for controlling the flow but while using the class component it's a bit difficult concerning the functional component. in functional components, the react-native lifecycle is very easy and simple. We can easily implement is using use effect hooks. It takes two parameters, the first one is a callback and the second one is a dependency array. useEffect works the same as the methods of class components.

Hooks: By using hooks you can implement components as functional components. hooks are introduced in react version 16.8. It simplifies the complex lifecycle method. We do not have to use the “this” keyword.

Let's see an example of functional components :

import React, {useState, useRef} from 'react';
import {Text, View} from 'react-native';
 
function App() {
  const [getString, setString] = useState('This is functional components example');
 
   return (
     <View>
        <Text style={{color:"blue"}}>hello learners {getString}</Text>
     </View>
   )
 
}
 export default App;

Output:

Lifecycle Of React Native Components

Here I have used useState hook. There are multiple hooks, we will be learning and using them in the other parts of this react-native tutorial.

React native team is also suggested to use functional components, here's the reason -

  1.  Simpler lifecycle.
  2. No need to use the “this” keyword, so simply less confusion.
  3. Easy to debug.
  4. We can use stateful logic without any change in the component hierarchy.

Hooks are a blessing for us. we should learn class components for sure but for efficient work we need to use functional components.


Related Topics

States in React Native

We can control data of components of react-native by state and props. We are familiar with props and used them multiple times previously. Props: This is used to customize components and...

3 minutes read.

React Native Status Bar

What is the status bar? The simplest and easiest answer to this question can be answered by looking at your mobile phone's top section. What can you see? Most probably, it's...

4 minutes read.

React Native Components

React Native components are the same as ordinary react components, but they are different in terms of rendering and styling. All react code lives in react components. They are independent...

16 minutes read.

Advantages and Disadvantages of React Native

Advantages of using React Native It is observed that React Native stands out from most of the existing methods of cross-platform application development, like Ionic or Cordova, because React Native renders...

3 minutes read.

Why to Learn React Native

The demand for smartphone applications is ever-changing. The elder ones disappear from our remembrances, and smartphones and new applications come each day. In this turbulent ecosystem, it is struggling for...

4 minutes read.

Basic knowledge of firebase for React Native

Firebase for react-native : Firebase is a mobile and web application development platform which is created in 2014 by google. It is a product of google which is offered to developers...

7 minutes read.

React Native Toast

Introduction: It is a message that will be displayed on the screen for a short span of time to interrupt the user. Primarily it is displayed by any user action....

5 minutes read.

TouchableOpacity in React Native

Touchable opacity is the most suited example if you want to make views respond to proper touch. If you want to control the opacity then it can be done by...

3 minutes read.

React Native API

API API stands for an Application programming interface. API allows communication between two software and is also responsible for data sharing. It takes the asked data from the server and delivers...

6 minutes read.

React Native Alert

In this part of the tutorial, we will learn about react-native's alert API. It is compatible with both android and IOS. What is API? Answer - API stands for Application programming interface,...

4 minutes read.

How Does React Native Work

Working of React Native React Native is a framework that lets us write android and iOS mobile applications using JavaScript. It is interesting to see how easy it is to develop...

4 minutes read.

What is a Bridge in React Native?

A React Native is generally composed of two fields or two parts: The first part is the code of JavaScript.The second one is native code. The ability to build a bridge between...

3 minutes read.

React Native indicator

React native activity indicator : React native activity indicator is one of the react-native components. We all have seen it several times. It's the loader. Look at the picture below - So now...

4 minutes read.

React Native Tutorial

Introduction to react native : React-native is an open-source javascript framework that can be used to develop native mobile apps for IOS and android. It is released by Facebook in 2015...

4 minutes read.

React native calender

In this article, we will be learning to add calendar features to react native app. So before creating the calendar, we do need to install a few packages or add some...

3 minutes read.

React Native stack navigation

You must know about the stack data structure. Stack is one of the important data structures which works in the FILO(first in last out) method. As you know, mobile apps are...

4 minutes read.

Difference Between React.js and React Native

React js vs. React-native React native:  react-native is an open-source javascript framework that can be used to develop native mobile apps for IOS and android. Facebook released it in 2015 and witnessed...

3 minutes read.

TouchableHighlight in React Native

It is just a wrapper for making touch work properly, and it is the conventional way of handling touch gestures. Today's most future-proof solution is pressable API. pressable manages all...

2 minutes read.

React Native Fonts

The font is one of the important essences of any good UI(User Interface). It is very important to have a clear and beautiful font in your app. In this module,...

4 minutes read.

Redux in React Native

 It is a really amazing library of javascript, react, and react-native. It is very popular in react native domain. Every react and react native developer must know the redux it...

7 minutes read.