3

As you know in useEffect we return the unsubscribe at the end if we assign any listener to unsubscribe const as shown under

As we Using

useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
        // code
    })
    return unsubscribe;

}, [navigation]);

As I want

useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
        // code
    })
    const unsubscribe2 = navigation.addListener('blur', () => {
        // code
    })

    // need to return both listeners

}, [navigation]);
AliRehman7141
  • 873
  • 3
  • 12
  • 33

2 Answers2

5

You can cleanup like this

useEffect(() => {

    navigation.addListener('focus', handler)
    navigation.addListener('blur', handler)
    return () => {
                navigation.removeListener('focus', handler)
                navigation.removeListener('blur', handler)
            }

},[navigation])

The official example here https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup

Someone Special
  • 12,479
  • 7
  • 45
  • 76
1

I didn't test this, but you might be able to do something like this:

useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
        // code
    });
    const unsubscribe2 = navigation.addListener('blur', () => {
        // code
    });
    return () => {
     // executed when unmount
     unsubscribe();
     unsubscribe2();
    }
}, [navigation]);
Eric
  • 543
  • 7
  • 17