In v1, you had to use tabBarOnPress for handling these use cases.

But v2 introduced a new feature, called NavigationEvents . We’ll take a closer look at both approaches.

Let’s consider the following TabNavigator:

// App.js import { createBottomTabNavigator } from "react-navigation"; export default createBottomTabNavigator({

Home: HomeScreen,

Settings: SettingsScreen

});

And the HomeScreen having the following content:

// HomeScreen.js import React from "react";

import { Text, View } from "react-native"; class HomeScreen extends React.Component {

render() {

return (

<View>

<Text>Home</Text>

</View>

);

}

}

Now, let’s say you want to do something when the user focuses the Home tab.

Approach #1: using NavigationEvents

As I’ve mentioned previously, react-navigation v2 introduced a new component, called NavigationEvents , that provides a declarative API to subscribe to typical navigation events, such as:

onWillFocus : before focusing a tab;

: before focusing a tab; onDidFocus : after focusing a tab;

: after focusing a tab; onWillBlur : before losing focus on a tab;

: before losing focus on a tab; onDidBlur : after losing focus on a tab;

Using this component is very easy and straightforward. You just have to include it in the screen that needs to be notified by these events, and specify the event handlers:

// HomeScreen.js ... import { NavigationEvents } from "react-navigation"; class HomeScreen extends React.Component {

render() {

return (

<View>

<NavigationEvents

onWillFocus={payload => {

console.log("will focus", payload);

}}

/> <Text>Home</Text>

</View>

);

}

}

Pros:

easy-to-use declarative API;

out-of-the-box subscribing on mount and unsubscribing on unmount;

Cons:

unable to prevent focusing on a tab;

unable to detect double tap;

So this approach solves only 2 out of 4 of our initial use cases. Next, we’ll take a look at another approach, which is imperative, but will offer us more flexibility.