2

I have a component that sets up a stack navigator (TabsWithSearch) with 1 bottom tab navigator (MainTabs)(that has screens in a stack navigators in it (FirstTabStack, SecondTabStack) and 1 screen (Search). The result I want to achieve is every screen in the tab navigator to have access to Search screen. Search has a "form" that you can type your query in an input and then update MyContext's search value with it.

Below you can find example code (not the whole component), but it represents my current set up.

const DEFAULT_SEARCH = {query: ""};
const [search, setSearch] = React.useState(DEFAULT_SEARCH);

const TabsWithSearch = createStackNavigator();
const MainTabs = createBottomTabNavigator();
const HomeStack = createStackNavigator();
const ExploreStack = createStackNavigator();

<MyContext.Provider value={{search, setSearch}}>
  <TabsWithSearch.Navigator>
  </TabsWithSearch.Navigator>
  <TabsWithSearch.Screen
    name="Main Tabs"
    component={MainTabsNavigator}
    options={{ headerShown: false }}
  />
  <TabsWithSearch.Screen
    name="Search"
    component={...search screen component}
    options={{
      headerShown: false,
      cardStyleInterpolator: CardStyleInterpolators.forModalPresentationIOS,
      mode: 'modal',
      cardStyle: {
        backgroundColor: 'transparent',
      },
    }}
  />
</MyContext.Provider>

Each Tab Screen uses the context like this:

const myContext = React.useContext(MyContext);
console.log(myContext.search);

And Search screen updates it like this:

const myContext = React.useContext(MyContext);
console.log(myContext.setSearch({query: "Test"});

The problem is that the entire screen refreshes, every time MyContext.search is updated. Which is expected, but how can I avoid it while still having access to MyContext throughout different screens.

Ivanka Todorova
  • 9,964
  • 16
  • 66
  • 103
  • 1
    Can you post your full code? Seems like you're creating components inside components which would recreate the screens causing them to unmount and remount. Make sure all of the component definitions are outside body of other components, at root of the file. – satya164 May 26 '20 at 21:59
  • @satya164, thank you so much! I indeed had all screen definitions inside the component. I moved them outside and now every time I update the context it doesn't refresh the app and my screens don't "blink" (unmount/mount) – Ivanka Todorova May 27 '20 at 08:27

0 Answers0