React Native: How To Re-Render on Focus change?

React Native: How To Re-Render on Focus change?

In This blog, We are gonna show you how to re-render On screen focus change or you can run any specific function on screen focus event. This is handy for sending more API calls when a user returns to a specific screen in a Tab Navigator or tracking user events as they tap around our app.

There are multiple methods are available to achieve this.

  1. Listening to the ‘focus‘ event with an event listener.
  2. Using the useFocusEffect hook provided by react-navigation.
  3. Using the useIsFocused hook provided by react-navigation.

First of All We are gonna need React-navigation Module Follow this guide to install and setup React-navigation in your project.

1. Using ‘focus’ Event To Trigger An action on Focus.

We will setup an event listener using react-navigation, But you can also setup using JavaScript event listener. After setting up the listener we also need to stop the event listener when the screen in unmounted. Only when the screen focuses will we be able to call an action with this method.

Example:

import * as React from 'react';
import { View } from 'react-native';

function DemoScreen({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // this part will run when screen will be focus
    });
    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

  return <View />;
}

This method is effective but we recommend using the hook ‘useFocusEffect‘ Which is provided by react-navigation. Continue reading below for more details.

2. Using Hook ‘useFocusEffect‘ To Trigger An Action.

React-navigation by default provide an hook know as ‘useFocusEffect’ which runs an action when screen comes to focus and then automatically clears when screen is unmounted. This is very useful when trying to fetch data from API or stop playing media when screen is not focused.

Let’s see an Example:

import { useFocusEffect } from '@react-navigation/native';

function Guest({ userId }) {
  const [user, setUser] = React.useState(null);

  useFocusEffect(
    React.useCallback(() => {
      const unsubscribe = API.subscribe(userId, user => setUser(data));

      return () => unsubscribe();
    }, [userId])
  );

  return <GuestContent user={user} />;
}

3. Using Hook ‘useIsFocused‘ to Re-render the Screen on Focus.

The Hook useIsFocused is also provided by default by React-navigation. But this hook only provide Boolean value, that is True or False.

This hook will return True when screen is focused and will return False when screen is unmounted. This allows us to render things conditionally depending on whether or not the user is present on the screen.

The Hook will Also re-render cause our component to re-render when focus of the screen changes. so, unnecessary re-renders may happen while using this hook. Use this hook only when you need to re-render screen.

Let’s Check the Example:

import * as React from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';
function Demo() {
  const isFocused = useIsFocused();// This hook returns `true` if the screen is focused, `false` otherwise
  return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}

 

Conclusions,

Using this three methods you can easily re-render your components or run an action when screen comes to focus.

If you have any doubts or query, Do let us know in the comments below we will try to solve it as soon as possible.

Do Follow Us on:

Facebook.com

Twitter.com

Also Checkout: Implement Android In-App Update API In React Native

About: Aakash Kothari

I am passionate about my work. Because I love what I do, I have a steady source of motivation that drives me to do my best. In my last job, this passion led me to challenge myself daily and learn new skills that helped me to do better work


Leave a Reply

%d bloggers like this: