1

As they point out in the docs, they've gotten rid of the 4 navigation event listeners and instead decided to use Lifecycle events.

But the problem I'm running into with React Navigation 5 is that the blur event doesn't work as I need it to! Before, I could add an onWillBlur listener, and do stuff when the user temporarily leaves (not closes) the app (such as close a socket connection, and then reopen it when the user reenters the app).

How can I replicate the onWillBlur or onDidBlur events for such a use case? I don't need to know if Screen A is blurred after the user is taken to Screen B after clicking a button.

Mike K
  • 7,621
  • 14
  • 60
  • 120

1 Answers1

1

You can use the hook useFocusEffect.

Documentation here

EDIT:

Added example from React Navigation.

import { useFocusEffect } from '@react-navigation/native';

function Profile() {
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused, onFocus


      return () => {
        // Do something when the screen is unfocused, onBlur
        // Useful for cleanup functions
      };
    }, [])
  );

  return <ProfileContent />;
}

EDIT 2:

I didn't test it on home button but I found a post that helps with that too

Check here

I hope this time you are pleased with my answer.

And here you have a working example :

import React from 'react'
import { Text, AppState } from 'react-native'

const MyComponent = () => {

    const [appState, setAppState] = React.useState(AppState.currentState)

    React.useEffect(() => {
      AppState.addEventListener('change', handleChanges)

      setAppState(AppState.currentState)

      return AppState.removeEventListener('change')
    },[])

    const handleChanges = (nextAppState) => {
        if (appState.match(/inactive|background/) && nextAppState === 'active') {

          console.log('App has come to the foreground!');
        } else {
          console.log('App has gone to the background!');
          // start your background task here
        }

        setAppState(nextAppState)
    }

    return  <Text>{appState}</Text>
}
CevaComic
  • 2,056
  • 2
  • 6
  • 12
  • This does not let you know if the screen blurred after a user clicks their Home button and leaves the app. – Mike K Apr 23 '20 at 06:26