React Native Call useEffect Only Once in Functional Component Example

In React Native class component life cycle there are 3 inbuilt functions named as componentDidMount, componentDidUpdate, and componentWillUnmount used to perform certain task on a certain condition. But in functional these three methods are not available and to perform their task here we would use  useEffect() method. The useEffect method is combined part of all three componentDidMount, componentDidUpdate, and componentWillUnmount methods. The useEffect calls each time when after rendering the screen. Even if we update State or define the method it will calls every time when render calls. To stop calling useEffect after every render we have to pass Array[] as argument in useEffect method. It will prevent the useEffect method to calling automatically. To run the useEffect once we have to pass the [] Array as Second argument so this would tell the react native that there are no state or prop needs to updated so it won’t run the useEffect again. So in this tutorial we would React Native Call useEffect Only Once in Functional Component Android iOS Example Tutorial.

Contents in this project React Native Call useEffect Only Once in Functional Component Android iOS Example Tutorial:

1. Open your project’s main App.js file and import useState, useEffect from React.

2. Import Alert, View, StyleSheet, Button and Text component.

3. Creating our main export default function App(). This is our Root functional component.

4. Creating a State named as count with state change function named as setCount. We would also set  the State value as Zero. To know more about How to use State in Functional Component read my this tutorial.

5. Creating useEffect() method and here we would set the count value as Zero again. We would also Show a alert dialog box on to see the effect on mobile screen. Now we would pass the Empty [] Array as second argument to stop useEffect to run again.

React Native Call useEffect Only Once in Functional Component Example

6. Creating Return Block and here we would make our Root View component and 1 Button component. We would increase value of Count to Plus +1 on every click event.

7. Complete Source Code for App.js file:

Screenshots:

Leave a Reply

Your email address will not be published.