8protons
8protons

Reputation: 3959

React Native + Expo: Splash screen close after wait time and when page complete

After initializing a template "tabs" Expo project, the startup routine for the React Native app looks as follows:

React.useEffect(() => {
  async function loadResourcesAndDataAsync() {
    try {
      SplashScreen.preventAutoHide();

      // Load our initial navigation state
      setInitialNavigationState(await getInitialState());

      // Load fonts
      await Font.loadAsync({
        ...Ionicons.font,
        'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
      });
    } catch (e) {
      // We might want to provide this error information to an error reporting service
      console.warn(e);
    } finally {
      setLoadingComplete(true);

      SplashScreen.hide();
    }
  }

  loadResourcesAndDataAsync();
}, []);

Expo's documentation on making the "splash screen stick around for longer" simply demonstrates:

import { SplashScreen } from 'expo';

SplashScreen.preventAutoHide();
setTimeout(SplashScreen.hide, 5000);

The problem is that I'd like the splash screen to stay up if the background/next view is still being rendered, as opposed to simply waiting for an arbitrary amount of time. For example, if render time takes 0.2 seconds, and I want the splash page to be up for 2 seconds, I'd like the splash page to close at 2 seconds. If the render time takes 2.8 seconds, I'd like the splash page to stay up for 2.8 seconds. What's the best way to achieve this?

Upvotes: 0

Views: 4539

Answers (1)

Chenhua
Chenhua

Reputation: 203

Try "componentDidMount" lifecycle function. react-lifecycle-methods-diagram

Here is the idea:

  1. render the splash screen first, in the 'componentDidMount' function of the splash screen, start to render the next screen / background part / additional part.
  2. Once the next screen / background class / additional class is rendered, in 'componentDidMount' of this class, update flag in state (of the splash class or global store like redux/mobox) to inform the splash screen 'it'ready to go'.
  3. finally, in splash screen, create a timer, after for example 2 seconds, check the flag in state every 100ms, if it's ready to go, then go.

By the way, if the next screen is not that slow to load, in my opinion it's a little bit over skill.

Upvotes: 1

Related Questions