Search code examples
javascriptreact-nativebackgroundworkerweb-worker

React-Native: run a function in background while component is loaded


In a component, while the listview and everything is loaded.

Is it possible to run a function in background to reload the listview data in every few minutes?

If yes, When user leaves the component ( go to another tab, iOS ), will the function stop?


Solution

  • You can do this by adding a setInterval in componentDidMount and clearing it in componentWillUnmount.

    let interval;
    class HelloWorld extends Component {
    
      componentDidMount() {
        interval = setInterval(() => {
    
            // do what you want here.
    
        }, 10000);
      }
    
      componentWillUnmount() {
        clearInterval(interval);
      }
    
      render() {
        return (
          <Text>Hello world!</Text>
        );
      }
    }