How to use useFocusEffect in React Navigation 5.x

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.

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

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

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

4. Output:

How to use useFocusEffect, useIsFocused in React Navigation 5

Thank you 🙂

Leave a Reply

Your email address will not be published.