Amphyx
Amphyx

Reputation: 755

Call function on application load in React Native

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',
  },
});

Upvotes: 6

Views: 30467

Answers (2)

Vladimir Salguero
Vladimir Salguero

Reputation: 5947

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',
    },
});

Upvotes: 5

Mahdi N
Mahdi N

Reputation: 2178

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

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

Upvotes: 6

Related Questions