Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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',
  },
});
like image 320
Amphyx Avatar asked Sep 08 '26 21:09

Amphyx


1 Answers

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

useEffect(() => {
// write your code here, it's like componentWillMount
}, [])
like image 55
Mahdi N Avatar answered Sep 11 '26 03:09

Mahdi N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!