import React, { useContext, useEffect, useRef } from "react";
import { ScrollView, StyleSheet, Text, View, TouchableOpacity } from "react-native";
// custom components
import Screen from "../components/Screen";
// context api
import { useNavigation } from "@react-navigation/native";
function HomeScreen(props) {
const navigation = useNavigation();
useEffect(() => {
alert("mount");
return () => {
alert("unmount");
};
}, []);
return (
<Screen>
<TouchableOpacity
onPress={() => navigation.navigate("CategoryList", { name: "Mark" })}
>
<Text>Mark</Text>
</TouchableOpacity>
</Screen>
);
}
export default HomeScreen;
First this component renders and alert message mount. Now when I navigate into the CategoryList screen, it successfully navigates into the CategoryList screen but, before navigating into the CategoryList screen, this HomeScreen re-renders, alert the messages mount and unmount both, then only it renders CategoryList screen. My question is if we are navigating into the CategoryList screen, then only CategoryList screen should render, isn't it ? Why HomeScreen re-renders then it goes to CategoryList screen. Even from CategoryList screen, if I go into another screen, then again it re-rerenders HomeScreen, then CategoryListScreen then another screen. So, is it the way it works or can we optimize re-renders ?
Navigation structure is like
App.js
return (
<AuthContext.Provider value={{ user, setUser }}>
<Store> //Store is a context provider where the SafeAreaView below has been passed as children props
<SafeAreaView style={styles.container}>
<NavigationContainer theme={navigationTheme}>
{user ? <AppNavigator /> : <AuthNavigator />}
</NavigationContainer>
</SafeAreaView>
</Store>
</AuthContext.Provider>
);
Inside AppNavigator.js
return (
<Tab.Navigator
tabBarOptions={{
showLabel: false,
activeBackgroundColor: colors.primary,
activeTintColor: colors.white
}}
>
<Tab.Screen
name="Home"
component={HomeNavigator}
options={{
tabBarIcon: ({size, color}) => <MaterialCommunityIcons size={size} color={color} name="home"/>
}}
/>
</Tab.Navigator>
);
Inside HomeNavigator.js
function HomeNavigator(props) {
const Stack = createStackNavigator();
const HomeScreenWrapper = () => {
return (
<HomeStore>
<HomeScreen />
</HomeStore>
);
};
// Given above HomeScreenWrapper is a function which returns HomeScreen component wrapping inside HomeStore which is a context provider for HomeScreen only
return (
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: colors.primary,
},
headerTintColor: colors.white,
}}
>
<Stack.Screen name="Home" component={HomeScreenWrapper} />
<Stack.Screen
name="CategoryList"
component={CategoryListScreen}
options={({ route }) => ({
title: route.params.name,
headerBackTitleVisible: false,
})}
></Stack.Screen>
</Stack.Navigator>
);
}
export default HomeNavigator;
And to see what's inside HomeScreen, Scroll to the top at first.