How to cache Screens in React Navigation?

154 views Asked by At

In React Navigation's StackNavigator, whenever I switch the current Screen, regardless of whether I've previously loaded the new Screen, it always reloads. This is not what I want; I want certain Screens to be cached after loading once. How can I achieve that?

import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

import Home from "@/screens/Home";
import Profile from "@/screens/Profile";
import Test from "@/screens/Test";
import Login from "@/screens/Login";

const Stack = createNativeStackNavigator();

export default function Router({ children }) {
  const screenList = [
    {
      name: "Home",
      component: Home,
      options: {
        gestureEnabled: false,
      },
    },
    {
      name: "Profile",
      component: Profile,
      options: {
        gestureEnabled: false,
      },
    },
    {
      name: "Test",
      component: Test,
      options: {
        gestureEnabled: false,
      },
    },
    {
      name: "Login",
      component: Login,
      options: {
        gestureEnabled: false,
      },
    },
  ];

  return (
    <NavigationContainer>
      <Stack.Navigator
        initialRouteName="Home"
        screenOptions={{
          animation: "none",
          headerShown: false,
        }}
      >
        {screenList.map((item, index) => {
          return (
            <Stack.Screen
              key={index}
              name={item.name}
              component={item.component}
              options={item.options}
            />
          );
        })}
      </Stack.Navigator>
      {children}
    </NavigationContainer>
  );
}

I've noticed that the BottomTabNavigator provided by React Navigation seems to prevent Screens contained within the tabBar from being reloaded. I'm not sure if I should use this.

0

There are 0 answers