In a react native project, I use Bottom Tab Navigation from React Navigation.
Within the file that initializes the navigation stack, I directly invoke a RTK query hook without using any of its returned value like data, isLoading, isUnitialized etc. Reason for this is so I can prefetch data needed in 2 unmounted screens, Events & Favorites, see code below.
// MainNavigator.tsx
export default function MainNavigator() {
// Pre-Fetch Events
useGetLatestEventsQuery();
return (
<Tabs.Navigator
initialRouteName="Tickets"
tabBar={(props) => (
<BottomTabBar
/>
)}
{/* Events */}
<Tabs.Screen
name="Events"
component={EventsNavigator}
/>
{/* Tickets */}
<Tabs.Screen name="Tickets" component={TicketsNavigator} />
{/* Favorites */}
<Tabs.Screen name="Favorites" component={FavoritesNavigator} />
...
In the Tickets Screen, I use the correct hook for fetching tickets as it is going to be the first screen on the navigation so there's no need to fetch the tickets data ahead of time. So, on both the Events & Favorites screen, I basically then use the useGetLatestEventsQuery
hook again but I skip the query at first so I can then use the refetch method from it to force the query again on refresh of the screen.
export default function Events() {
const events = useSelector((state: RootState) => state.event.events);
const [skipQuery, setSkipQuery] = useState(true);
const { isFetching, refetch, isUninitialized } = useGetLatestEventsQuery(
undefined,
{ skip: skipQuery }
);
const handleRefresh = () => {
isUninitialized ? setSkipQuery(true) : refetch();
};
return (
<Layout
refreshing={isFetching}
onRefresh={handleRefresh}
emptyScreen={events?.length === 0}
loading={events === null || isFetching}
>
<EventsCarousel events={events ?? []} />
</Layout>
);
}
Is this approach considered anti-pattern?
As you mentioned in comment, your goal is to reduce display time for tab components. So your solution is not anti-pattern, but it's not very self-explanatory. You can use Redux Toolkit Prefetch which achieve the same goal than you solution, and will be simpler for other developer to understand.