Skip to content

Instantly share code, notes, and snippets.

@bacarybruno
Created August 13, 2021 08:56
Show Gist options
  • Save bacarybruno/a67813e3ae068c63100ab5b18b1a5428 to your computer and use it in GitHub Desktop.
Save bacarybruno/a67813e3ae068c63100ab5b18b1a5428 to your computer and use it in GitHub Desktop.
import { useEffect, useState, useContext } from 'react'
import { NavigationContext } from 'react-navigation'
export const useNavigation = () => {
const navigation = useContext(NavigationContext)
if (!navigation) {
throw new Error('navigation object not found. Please make sure your component is in a navigation tree')
}
return navigation
}
export const useIsFocused = () => {
const navigation = useNavigation()
const [isFocused, setIsFocused] = useState(navigation.isFocused())
useEffect(() => {
const willFocus = navigation.addListener('willFocus', () => setIsFocused(true))
const willBlur = navigation.addListener('willBlur', () => setIsFocused(false))
return () => {
willFocus.remove()
willBlur.remove()
}
}, [navigation])
return isFocused
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment