How to detect first launch of react native app using hooks?

Viewed 1327

I'm trying to code a screen in react native that only shows upon first downloading the app, and I found some reference code that shows what I'm trying to do, but I'm not sure how to implement it using react hooks instead of the class component style they used here. Also I discovered that componentWillMount() is deprecated so I wanted to figure out which hook to use to replace it?

Note that checkIfFirstLaunch is a function I wrote to check if it is the first time the app has launched. I essentially need help turning this into a functional component.

import React from 'react';
import { Text } from 'react-native';
import checkIfFirstLaunch from './utils/checkIfFirstLaunch';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isFirstLaunch: false,
      hasCheckedAsyncStorage: false,
    };
  }

  async componentWillMount() {
    const isFirstLaunch = await checkIfFirstLaunch();
    this.setState({ isFirstLaunch, hasCheckedAsyncStorage: true });
  }

  render() {
    const { hasCheckedAsyncStorage, isFirstLaunch } = this.state;

    if (!hasCheckedAsyncStorage) {
      return null;
    }

    return isFirstLaunch ?
      <Text>This is the first launch</Text> :
      <Text>Has launched before</Text>
    ;
  }
}
1 Answers

You can use useEffect to do the same work as componentDidMount (componentWillMount is deprecated and not exist in functional component)

Return null while your test is not executed, then check your boolean

import React, { useEffect, useState } from 'react';
import { Text } from 'react-native';
import checkIfFirstLaunch from './utils/checkIfFirstLaunch';

const App = () => {
    const [isFirstLaunch, setIsFirstLaunch] = useState(null)

    useEffect(() => {
        checkIfFirstLaunch().then((isFirstLaunch) => {
            setIsFirstLaunch(isFirstLaunch)
        });
    }, [])

    if (isFirstLaunch === null) return null

    return isFirstLaunch ?
      <Text>This is the first launch</Text> :
      <Text>Has launched before</Text>
    ;
}

export default App
Related