Navigation Lifecycle

When the user navigates from scene A to scene B then the first scene isn't unmounted. It's still mounted because it stays in the stack. When the user navigates back then scene B is popped and scene A reappears. The Navigation router has a useNavigated hook that tells you when the user navigates to scene A. It also has a useUnloaded hook that tells you when the user navigates away from scene A to scene B.

The 'inbox' scene in our example app polls an endpoint to check if the user has any new mail. We can use the scene lifecycle hooks to make sure we only poll when the user is browsing their inbox. We stop the polling when the user navigates to an email and then start it again when they go back to their inbox.

import {useNavigated, useUnloaded} from 'navigation-react-native';

const Inbox = () => (
  useNavigated(() => {
    // Start polling for new emails
  });
  useUnloaded(() => {
    // Stop polling for new emails
  });

Peeking Back on iOS

On iOS, when the user is reading a mail they can half swipe left so they can peek at their inbox without navigating to it. We want to show them their latest mail but we don't want to start polling because they're still on the 'email' scene. The Navigation router has a useNavigating hook that notifies us when the swipe starts. We use this to issue a one-time call to refresh the inbox. If the user completes the swipe the useNavigated fires and we start polling again.

import {useNavigating} from 'navigation-react-native';

useNavigating(() => {
  // Fetch new emails
});