Education
Developer Advocate
Last updated onOct 26, 2023
Last updated onSep 27, 2023
The useFocusEffect is a hook provided by the React Navigation library in React Native. It is designed to run side effects (like fetching data, subscribing to events, etc.) when a screen comes into focus and cleans them up when it goes out of focus. This is particularly useful in mobile applications where screens can come in and out of focus frequently, and you want to ensure that you're not wasting resources or causing unnecessary re-renders.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function Profile() { 4 useFocusEffect( 5 React.useCallback(() => { 6 // Do something when the screen is focused 7 8 return () => { 9 // Do something when the screen is unfocused 10 // Useful for cleanup functions 11 }; 12 }, []) 13 ); 14 15 // ... 16 } 17
In the example above, the useFocusEffect hook is used within a function component in React Native. The function passed to useFocusEffect will run when the screen is focused and will cleanup when the screen goes out of focus. The only difference between useFocusEffect and React's useEffect hook is that useFocusEffect only runs the effect when the screen is focused.
React Navigation is a popular library in React Native for handling navigation and the transition between screens in your app. The useFocusEffect hook is a part of this library and plays a crucial role in managing resources and improving performance.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function HomeScreen({ navigation }) { 4 useFocusEffect( 5 React.useCallback(() => { 6 const unsubscribe = API.subscribe(); 7 8 return () => unsubscribe(); 9 }, []) 10 ); 11 12 return ( 13 // ... 14 ); 15 } 16
In this example, the useFocusEffect hook is used to subscribe to an API when the HomeScreen is focused and unsubscribe when it is not. This ensures that we're not keeping unnecessary subscriptions open and wasting resources when the user is not on this screen.
The useEffect hook is a built-in hook in React that allows you to perform side effects in function components. Side effects are basically anything that interacts with the world outside of the function component (like fetching data, subscribing to events, etc.). The useEffect hook runs after every render, including the initial render.
On the other hand, the useFocusEffect hook in React Navigation is a bit different. It only runs the effect when the screen is focused, and it cleans up the effect when the screen is unfocused or when the component unmounts. This is the only difference between useEffect and useFocusEffect. This behavior makes useFocusEffect more suitable for mobile applications where screens frequently come in and out of focus.
Fetching data and listening to events are common tasks in any React Native application. The useFocusEffect hook can be particularly useful in these scenarios. It allows you to fetch data or set up an event listener when the screen comes into focus and clean up when it goes out of focus.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function NewsScreen() { 4 useFocusEffect( 5 React.useCallback(() => { 6 const fetchData = async () => { 7 // Fetch data here 8 }; 9 10 fetchData(); 11 12 return () => { 13 // Clean up here 14 }; 15 }, []) 16 ); 17 18 return ( 19 // ... 20 ); 21 } 22
In this example, we're using the useFocusEffect hook to fetch data when the NewsScreen is focused. The cleanup function will run when the screen is unfocused, allowing us to cancel any ongoing fetch requests or clean up any resources used during the fetch.
The cleanup function in useFocusEffect is crucial for preventing memory leaks and ensuring optimal performance. It runs when the screen is unfocused or when the component unmounts, allowing you to clean up any resources used during the effect.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function ChatScreen() { 4 useFocusEffect( 5 React.useCallback(() => { 6 const eventListener = Event.addListener('newMessage', handleNewMessage); 7 8 return () => { 9 // Remove the event listener when the screen is unfocused 10 eventListener.remove(); 11 }; 12 }, []) 13 ); 14 15 return ( 16 // ... 17 ); 18 } 19
In this example, we're using the useFocusEffect hook to set up an event listener when the ChatScreen is focused. The cleanup function removes the event listener when the screen is unfocused, ensuring that we're not keeping unnecessary listeners open and wasting resources.
Both useFocusEffect and useIsFocused are hooks provided by the React Navigation library in React Native. While they both relate to the focus state of a screen, they serve different purposes.
The useFocusEffect hook is used to run side effects when a screen comes into focus and clean them up when it goes out of focus. On the other hand, useIsFocused is a hook that simply returns a boolean indicating whether the screen is currently focused or not.
1 import { useIsFocused } from '@react-navigation/native'; 2 3 function ProfileScreen() { 4 const isFocused = useIsFocused(); 5 6 return ( 7 <Text>{isFocused ? 'Focused' : 'Not focused'}</Text> 8 ); 9 } 10
In this example, the useIsFocused hook is used to display a text indicating whether the ProfileScreen is currently focused or not. This can be useful for conditional rendering based on the focus state of the screen.
While useFocusEffect is a hook provided by the React Navigation library for React Native, the concept can also be applied in a web context using React Router. For instance, you might want to fetch data when a route comes into view and cancel the fetch when it goes out of view.
1 import { useEffect } from 'react'; 2 import { useLocation } from 'react-router-dom'; 3 4 function NewsPage() { 5 const location = useLocation(); 6 7 useEffect(() => { 8 const fetchData = async () => { 9 // Fetch data here 10 }; 11 12 fetchData(); 13 14 return () => { 15 // Cancel fetch here 16 }; 17 }, [location]); 18 19 return ( 20 // ... 21 ); 22 } 23
In this example, we're using the useEffect hook from React and the useLocation hook from React Router to mimic the behavior of useFocusEffect. The effect will run when the location changes (i.e., when the route comes into view), and the cleanup function will run when the location changes again (i.e., when the route goes out of view).
The useFocusEffect hook in React Navigation provides a way to handle focus and blur events in your React Native application. Focus events occur when a screen comes into focus, while blur events occur when a screen goes out of focus.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function SettingsScreen() { 4 useFocusEffect( 5 React.useCallback(() => { 6 console.log('Screen is focused'); 7 8 return () => { 9 console.log('Screen is unfocused'); 10 }; 11 }, []) 12 ); 13 14 return ( 15 // ... 16 ); 17 } 18
In this example, the useFocusEffect hook is used to log a message to the console when the SettingsScreen is focused and another message when it is unfocused. This can be useful for debugging or for performing certain actions only when the screen is in view.
The useFocusEffect hook is a powerful tool in React Navigation for managing resources and improving performance in your React Native application. By understanding how it works and how it differs from other hooks like useEffect and useIsFocused, you can write more efficient and effective code.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.