ReactNative Class and Hook component Lifecycle

Sanjana Human In Tech
4 min readOct 24, 2023

--

React Native is a popular framework for building mobile applications using JavaScript and React. It allows you to develop mobile apps for both iOS and Android platforms. React Native components have lifecycles, just like React components. These lifecycles allow you to perform actions at different stages of a component’s existence.

Here are the main lifecycle methods in React Native:

                            [Constructor]
|
V
+----------------+
| Component is |
| Created |
| |
+----------------+
|
V
+----------------+
| Component Will |
| Receive |
| New Props |
+----------------+
|
V
+----------------+
| Render |
| Component |
+----------------+
|
V
+----------------+
| Component Did |
| Mount |
+----------------+
|
V
+----------------+
| Component Will |
| Unmount |
+----------------+

Class component Lifecycle :
1. constructor(): The constructor is called before the component is mounted. It’s used to initialize state and bind event handlers.

2. componentDidMount(): This method is called after the component has been rendered to the screen. It’s often used to fetch data from an API or perform other initialization tasks that require the component to be on the screen.

3. componentDidUpdate(prevProps, prevState): This method is called after a component’s state or props have changed and the component has re-rendered. It’s useful for responding to changes in the component’s data.

4. shouldComponentUpdate(nextProps, nextState): This method is used to control whether a component should re-render when its props or state change. By default, it returns true, but you can override it to optimize performance.

5. componentWillUnmount(): This method is called just before the component is unmounted from the screen. It’s used to clean up any resources, such as event listeners or timers, to prevent memory leaks.

import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';

class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}

componentDidMount() {
// This method is called after the component is rendered to the screen.
console.log('Component is mounted.');
}

componentDidUpdate(prevProps, prevState) {
// This method is called after the component's state or props have changed.
console.log('Component updated. Previous state:', prevState);
}

componentWillUnmount() {
// This method is called just before the component is unmounted.
console.log('Component is about to unmount.');
}

handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
}

render() {
return (
<View>
<Text>Count: {this.state.count}</Text>
<Button title="Increment" onPress={this.handleIncrement} />
</View>
);
}
}

export default MyComponent;

In React Native, functional components with hooks have a different approach to managing component lifecycles compared to class components.

Instead of having lifecycle methods like in-class components, hooks provide specific functions that you can use to manage component state and side effects. H

useState and useEffect for ComponentDidMount and ComponentDidUpdate:

Below example; useEffect function is called after the initial render (similar to componentDidMount) and whenever the count state changes (similar to componentDidUpdate).

import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';

function MyComponent() {
const [count, setCount] = useState(0);

useEffect(() => {
// ComponentDidMount and ComponentDidUpdate combined
console.log('Component is mounted or updated.');
}, [count]);

const handleIncrement = () => {
setCount(count + 1);
}

return (
<View>
<Text>Count: {count}</Text>
<Button title="Increment" onPress={handleIncrement} />
</View>
);
}

export default MyComponent;
useEffect(() => {
// Your code here
}, []);

Notice the second parameter here (empty array). This will run only once.

Without the second parameter, the useEffect hook will be called on every render of the component which can be dangerous.

useEffect(() => {
// Your code here
});

2. useEffect for ComponentWillUnmount:

useEffect(() => {
window.addEventListener('mousemove', () => {});

// returned function will be called on component unmount
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';

function MyComponent() {
const [count, setCount] = useState(0);

useEffect(() => {
// ComponentDidMount
console.log('Component is mounted.');

// ComponentWillUnmount
return () => {
console.log('Component is unmounted.');
};
}, []);

const handleIncrement = () => {
setCount(count + 1);
}

return (
<View>
<Text>Count: {count}</Text>
<Button title="Increment" onPress={handleIncrement} />
</View>
);
}

export default MyComponent;

In this example, we use the useEffect hook to mimic componentDidMount, and we return a cleanup function to mimic componentWillUnmount. The cleanup function is executed when the component is unmounted.

By using hooks in functional components, you can effectively manage component state and side effects, replicating the behavior of class component lifecycle methods.

These examples cover some common use cases, but there are many other hooks available for specific purposes, such as useContext for working with context and useReducer for more complex state management. You can compose hooks to create custom lifecycle behaviors as needed for your React Native application.

Thank you for reading this article! Don’t forget to clap 👏 .

If you have any queries related to ReactNative, I’m always happy to help you. You can reach me on LinkedIn and gmail.

Happy Learning🚀 Happy Coding💻.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

No responses yet