Education
Developer Advocate
Last updated onOct 26, 2023
Last updated onSep 26, 2023
React Navigation is a powerful library for navigating between different screens in a React Native app. One of the hooks it provides is useIsFocused. This hook returns a boolean indicating whether the screen is currently focused or not. It is useful when you want to perform certain actions only when the screen is in focus. For example, you might want to fetch data from an API only when the screen is focused to avoid unnecessary network requests.
1 import { useIsFocused } from '@react-navigation/native'; 2 3 function ProfileScreen() { 4 const isFocused = useIsFocused(); 5 6 return ( 7 <View> 8 {isFocused ? <Text>Screen is focused</Text> : null} 9 </View> 10 ); 11 } 12
In the above code, useIsFocused is used to determine if the ProfileScreen is currently in focus. If it is, a text component indicating that the screen is focused is rendered. Otherwise, nothing is rendered.
Another useful hook provided by React Navigation is useFocusEffect. This hook runs side effects (functions or operations that interact with the outside world, like fetching data, logging, or subscribing to events) when the screen comes into focus and cleans them up when it goes out of focus. It is similar to the useEffect hook in React, but it is tied to the focus state of the screen.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function ProfileScreen() { 4 useFocusEffect( 5 React.useCallback(() => { 6 // Do something when the screen is focused 7 return () => { 8 // Do something when the screen is unfocused 9 }; 10 }, []) 11 ); 12 13 return <View />; 14 } 15
In the above code, useFocusEffect is used to run a callback function when the ProfileScreen comes into focus and clean it up when it goes out of focus. The callback function is wrapped in React.useCallback to prevent it from changing on every render, which could lead to unnecessary side effects.
While both useFocusEffect and useIsFocused are related to the focus state of a screen, they serve different purposes and are used in different scenarios. useIsFocused simply returns a boolean indicating whether the screen is focused or not. It is a passive hook that provides information about the focus state.
On the other hand, useFocusEffect is an active hook that allows you to run side effects based on the focus state. It is similar to useEffect but tied to the focus state of the screen. You can use it to perform actions when the screen comes into focus and clean up when it goes out of focus.
1 import { useIsFocused, useFocusEffect } from '@react-navigation/native'; 2 3 function ProfileScreen() { 4 const isFocused = useIsFocused(); 5 6 useFocusEffect( 7 React.useCallback(() => { 8 if (isFocused) { 9 // Do something when the screen is focused 10 } 11 return () => { 12 if (!isFocused) { 13 // Do something when the screen is unfocused 14 } 15 }; 16 }, [isFocused]) 17 ); 18 19 return <View />; 20 } 21
In the above code, both useIsFocused and useFocusEffect are used. The useFocusEffect hook runs side effects based on the value returned by useIsFocused.
In React, you can use the useEffect hook to run a function automatically after the component renders and whenever certain dependencies change. This is useful for performing side effects, such as fetching data, subscribing to events, or updating the document title.
1 import React, { useEffect } from 'react'; 2 3 function ProfileScreen() { 4 useEffect(() => { 5 // This function will run automatically after the component renders 6 fetchData(); 7 }, []); // The empty array means this effect will only run once after the initial render 8 9 return <View />; 10 } 11
In the above code, useEffect is used to call the fetchData function automatically after the ProfileScreen component renders. The empty array as the second argument to useEffect means that the effect will only run once after the initial render, and not on subsequent re-renders.
React Navigation provides several types of navigators to manage the transition between screens in your app. The most commonly used ones are:
Each navigator comes with its own set of configuration options and methods, allowing you to customize the navigation experience to suit your app's needs.
As mentioned earlier, useFocusEffect is a hook provided by React Navigation that allows you to run side effects when a screen comes into focus and clean them up when it goes out of focus. It is similar to the useEffect hook in React, but it is tied to the focus state of the screen.
One important thing to note about useFocusEffect is that it does not run the effect immediately after the component renders, like useEffect does. Instead, it waits until the screen is fully focused. This can be useful in scenarios where you want to delay fetching data or performing some other side effect until the screen transition animation has completed.
1 import { useFocusEffect } from '@react-navigation/native'; 2 3 function ProfileScreen() { 4 useFocusEffect( 5 React.useCallback(() => { 6 const unsubscribe = API.subscribe(); 7 8 return () => { 9 unsubscribe(); 10 }; 11 }, []) 12 ); 13 14 return <View />; 15 } 16
In the above code, useFocusEffect is used to subscribe to some API when the ProfileScreen comes into focus and unsubscribe when it goes out of focus. The subscription is not made until the screen is fully focused, and it is cleaned up as soon as the screen starts going out of focus.
In React, you can use the useRef and useEffect hooks to determine if an element is focused. The useRef hook creates a reference to an element, and the useEffect hook allows you to run side effects after the component renders.
1 import React, { useRef, useEffect } from 'react'; 2 3 function TextInputWithFocusButton() { 4 const inputEl = useRef(null); 5 6 useEffect(() => { 7 if (inputEl.current === document.activeElement) { 8 console.log('Input element is focused'); 9 } 10 }); 11 12 return ( 13 <div> 14 <input ref={inputEl} type="text" /> 15 <button onClick={() => inputEl.current.focus()}>Focus the input</button> 16 </div> 17 ); 18 } 19
In the above code, useRef is used to create a reference to the input element, and useEffect is used to check if the input element is the currently active element in the document. If it is, a message is logged to the console.
Let's look at some practical examples of how useIsFocused and useFocusEffect can be used in a React Navigation app.
1 import { useIsFocused, useFocusEffect } from '@react-navigation/native'; 2 3 function ProfileScreen() { 4 const isFocused = useIsFocused(); 5 6 useFocusEffect( 7 React.useCallback(() => { 8 if (isFocused) { 9 console.log('Screen is focused'); 10 } 11 return () => { 12 if (!isFocused) { 13 console.log('Screen is unfocused'); 14 } 15 }; 16 }, [isFocused]) 17 ); 18 19 return <View />; 20 } 21
In the above code, useIsFocused is used to determine if the ProfileScreen is currently in focus. If it is, a message is logged to the console. When the screen goes out of focus, another message is logged to the console. This can be useful for debugging focus-related issues in your app.
In conclusion, useIsFocused and useFocusEffect are powerful hooks provided by React Navigation that allow you to interact with the focus state of your screens. Whether you need to fetch data when a screen comes into focus, clean up resources when it goes out of focus, or simply determine if a screen is currently focused, these hooks have you covered. By understanding and using these hooks effectively, you can create a smoother and more responsive navigation experience in your React Native apps.
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.