Search code examples
react-nativeuse-effectreact-navigation-v5focuslistener

How to use focus and blur listener in single useEffect react native


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]);

Solution

  • 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