Without React.useCallback
When you go onto the page, it will focus, and thus run the effect, and run the subscribe.
When you leave the page, it will run cleanup and thus un-subscribe.
With React.useCallback
If we have a state that is in dependency array, and that state changes, then it will make the React.useCallback re-generate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import React, {useState} from 'react'; import { View, Button } from 'react-native'; import { NavigationContainer, useFocusEffect } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; function ProfileScreen() { const [topic, setTopic] = useState('/topic/a'); useFocusEffect( // cached React.useCallback(() => { alert(`ProfileScreen was focused. ${topic}`); return () => { alert(`ProfileScreen was unfocused. ${topic}`); }; }, [topic]) ); return <View> <Button title="Press me" onPress={() => setTopic('/topic/z')} /> </View>; } function HomeScreen() { return <View />; } const Tab = createBottomTabNavigator(); export default function App() { return ( <NavigationContainer> <Tab.Navigator> <Tab.Screen name="Home" component={HomeScreen} /> <Tab.Screen name="Profile" component={ProfileScreen} /> </Tab.Navigator> </NavigationContainer> ); } |