Detect focus/blur on a React-Native screen

If you are developing a RN mobile application using a tab navigation with React-Navigation plugin for example, you might need to know when a screen is active or not.

➡ Step 1: Add listener functions

First in your constructor method, you have to add two listeners on this.props.navigation element.

Focus & Blur

The code in the constructor method to detect the focus and the blur events is the following:


constructor(props) {
    super(props);
    this.state = {
        ...
    };
    this.willFocusListener = this.props.navigation.addListener('willFocus', () => {
        this.componentWillFocus();
    });
    this.didBlurListener = this.props.navigation.addListener('didBlur', () => {
        this.componentDidBlur();
    });
}

willFocus is used to do an action just before the screen is visible for the user.
didBlur is used to do an action just after the screen is hide for the user.

➡ Step 2: Callback functions

Now, add the two callbacks for the two differents events:


componentWillFocus() {
    Alert.alert('focus');
}

componentDidBlur() {
    Alert.alert('blur');
}

➡ Step 3: Remove listener when screen is destroyed

When the screen is being unmounted, do not forget to kill the two listeners you added on step 1.
Just add the componentWillUnmount()


componentWillUnmount() {
    this.didFocusListener.remove();
    this.didBlurListener.remove();
}

➡ Result

Here you go. You should get something like this:

🔗 Useful links