NavigationContext
NavigationContext
provides the navigation
object (similar to the navigation prop). In fact, withNavigation uses this context to inject the navigation
prop to your wrapped component. The hook counterpart is essentially an useContext
with this context as well.
Most of the time, you won't use NavigationContext
directly, as the provided withNavigation
and hooks already cover most use cases. But just in case you have something else in mind, NavigationContext
is available for you to use.
Example with hooks
import { useState, useContext, useEffect } from 'react';
import { NavigationContext } from 'react-navigation';
export function useFocusState() {
const navigation = useContext(NavigationContext);
const isFocused = navigation.isFocused();
const [focusState, setFocusState] = useState(getInitialFocusState(isFocused));
function handleEvt(e) {
const newState = focusStateOfEvent(e.type);
newState && setFocusState(newState);
}
useEffect(() => {
const subsA = navigation.addListener('action', handleEvt);
const subsWF = navigation.addListener('willFocus', handleEvt);
const subsDF = navigation.addListener('didFocus', handleEvt);
const subsWB = navigation.addListener('willBlur', handleEvt);
const subsDB = navigation.addListener('didBlur', handleEvt);
return () => {
subsA.remove();
subsWF.remove();
subsDF.remove();
subsWB.remove();
subsDB.remove();
};
});
return focusState;
}