useNavigation
useNavigation is a hook that gives access to navigation object. It's useful when you cannot pass the navigation object as a prop to the component directly, or don't want to pass it in case of a deeply nested child.
It can be used in two ways.
Getting the navigation object by screen name
The hook accepts the name of the current screen or any of its parent screens to get the corresponding navigation object:
- Static
- Dynamic
import { useNavigation } from '@react-navigation/native';
function MyBackButton() {
const navigation = useNavigation('Profile');
return (
<Button
onPress={() => {
navigation.goBack();
}}
>
Back
</Button>
);
}
import { useNavigation } from '@react-navigation/native';
function MyBackButton() {
const navigation = useNavigation('Profile');
return (
<Button
onPress={() => {
navigation.goBack();
}}
>
Back
</Button>
);
}
Getting the current navigation object
You can also use useNavigation without any arguments to get the navigation object for the current screen:
function MyComponent() {
const navigation = useNavigation();
return <Button onPress={() => navigation.goBack()}>Go back</Button>;
}
This is often useful for re-usable components that are used across multiple screens.
See the documentation for the navigation object for more info.
Using with class component
You can wrap your class component in a function component to use the hook:
class MyBackButton extends React.Component {
render() {
// Get it from props
const { navigation } = this.props;
}
}
// Wrap and export
export default function (props) {
const navigation = useNavigation();
return <MyBackButton {...props} navigation={navigation} />;
}