Home » React-native » How to use useFocusEffect in React Navigation 5.x

How to use useFocusEffect in React Navigation 5.x

Pro Level React-native

Hi everyone, In this article, we are going to learn about How to use useFocusEffect in React Navigation 5.x. React Navigation is the most important dependency used to navigate between screens in React native and as the version changes, there are some changes in syntax. so in this article, we will learn about onResume call in react-navigation 5.x. In React-Navigation 5.x to refresh the screen, we need to use useFocusEffect and useIsFocused 

  • useFocusEffect: Use to trigger any function or method with screen gets focused or unfocused.
  • useIsFocused: Use to refresh UI components from the return method when the screen gets focused or unfocused.

To understand how it works, let’s create a new project

1. Create a new project

Use the following command to create a new project. also, you need to install react-navigation and react-navigation-stack so run the following command step by step.

//Create new project 
react-native init ProjectName

//Install react-navigation 5.x
npm install @react-navigation/native

//Install supported dependencies
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

//Install react-navigation stack
npm install @react-navigation/stack

//Install react-native-safe-area-context
npm install react-native-safe-area-context

After the successful installation of all the above dependencies we have to create two screens HomeScreen.js and CartScreen.js. and most important to setup react-navigation 5 in App.js

2. Setup React Navigation 5 in App.js

Import following components in App.js in order to run react-navigation 5,x

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {SafeAreaProvider} from 'react-native-safe-area-context';

import HomeScreen from './components/Home';
import CartScreen from './components/Cart';

import {enableScreens} from 'react-native-screens';

enableScreens(false);

const Stack = createStackNavigator();

export default function App() {
  return (
    <SafeAreaProvider>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="Home" component={HomeScreen}  options={{ title: 'Techup.co.in' }}/>
          <Stack.Screen name="Cart" component={CartScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </SafeAreaProvider>
  );
}

Now I have to use useFocusEffect, useIsFocused in Home.js before that we have to navigate the screen from Home.js to Cart.js to do this let’s understand Home.js source code

3. Home.js

In Home.js in I have added useFocusEffect & function to navigate to cart.js

import React, {useState} from 'react';

import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import { useIsFocused, useFocusEffect } from '@react-navigation/native';


export default function Home({ navigation }) {

 // Function triggers when screen gets focused or unfocused
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused.
      alert('Home Screen was focused');
      return () => {
     // Do something when the screen is unfocused
        alert('Home Screen was unfocused');
      };
    }, [])
  );

 //Const function to navigate to cart screen
  const openCartScreen = () => {
    navigation.navigate('Cart');  
  };

  return (
    <View>
      <Text
        style={{
          fontSize: 30,
          textAlign: 'center',
          margin: 30,
          color: '#0b44c5',
        }}>
        How to use useFocusEffect, useIsFocused in React native
      </Text>
     
      <TouchableOpacity
        onPress={openCartScreen}
        style={{
          alignItems: 'center',
          padding: 5,
          borderColor: 'black',
          borderWidth: 1,
          margin: 10,
          backgroundColor: '#2b65ea',
        }}>
        <Text style={{fontSize: 20, color: 'white'}}>Open cart screen</Text>
      </TouchableOpacity>
    </View>
  );
}

If useIsFocused returns true then the screen is focused and if it returns false then the screen gets unfocused
you need to use const isFocused = useIsFocused(); to get boolean value and you can use this isFocused in return method like below

function Home() {
  const isFocused = useIsFocused();
  return <View><Text>{isFocused ? 'screen focused' : 'screen unfocused'}</Text></View>;
}

4. Output:

How to use useFocusEffect, useIsFocused in React Navigation 5

Thank you 🙂

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *