Call function on application load in React Native

13,070

Solution 1

since you're using a stateless component, you can use the useEffect hook

useEffect(() => {
// write your code here, it's like componentWillMount
}, [])

Solution 2

You must add useEffect

import React, { useState, Component, useEffect } from 'react';
import { View, Text } from 'react-native';
import { getText } from '..components/getText';

export default function HomeScreen() {

    const [onLoadText, setText] = useState("");

    const onScreenLoad = () => {
        setText(getText());
    }
    useEffect(() => {
        // write your code here, it's like componentWillMount
        onScreenLoad();
    }, [])

    return (
        <View style={styles.container}>
            <Text>{onLoadText}</Text>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
});
Share:
13,070
Amphyx
Author by

Amphyx

Updated on June 04, 2022

Comments

  • Amphyx
    Amphyx almost 2 years

    I have a React Native application and it has tabbed layout. I need to call some function when the main screen is loaded. I tried to use componentWillMount() function, but it didn't work because my screen was defined in function and not in class. How can I create on load function?

    HomeScreen.js

    import React, { useState, Component } from 'react';
    import { View, Text } from 'react-native';
    import { getText } from '..components/getText';
    
    export default function HomeScreen() {
    
      const [onLoadText, setText] = useState("");
    
      const onScreenLoad = () => {
        setText(getText());
      }
    
      const componentWillMount = () => {
        // Not working
        onScreenLoad();
      }
    
      return (
        <View style={styles.container}>
          <Text>{onLoadText}</Text>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
      },
    });