T
TanStack3y ago
hilarious-sapphire

How do I get background refresh working in React Native like web?

I'm working on my React Native app currently and I'm trying to get React Query to mimic the background refresh behavior like it does on web. Currently looking at these docs but the solutions don't seem to be working for me. Any tips? https://tanstack.com/query/v4/docs/react/react-native
React Native | TanStack Query Docs
React Query is designed to work out of the box with React Native, with the exception of the devtools, which are only supported with React DOM at this time. There is a 3rd party Flipper plugin which you can try: https://github.com/bgaleotti/react-query-native-devtools
3 Replies
hilarious-sapphire
hilarious-sapphireOP3y ago
Stack Overflow
React-native : Stop an automatic refetch when screen is unmounted
I am using React-native and React-query and I want stop the automatic refetch when the screen is unmounted. Currently, when I go to my target screen, I call a query with an interval parameter : con...
eastern-cyan
eastern-cyan3y ago
Window Focus Refetching | TanStack Query Docs
If a user leaves your application and returns and the query data is stale, TanStack Query automatically requests fresh data for you in the background. You can disable this globally or per-query using the refetchOnWindowFocus option: Disabling Globally
hilarious-sapphire
hilarious-sapphireOP3y ago
I learned that React Navigation actually as a useFocusEffect for cases like this where you may want to refetch on focus. Paired with React Query, it works perfectly.
const {
data: userProfile,
refetch: refetchProfile,
isStale: profileIsStale,
} = useGetUserProfile();

const { mutate: signOut } = useSignOut();

useFocusEffect(
useCallback(() => {
const unsubscribe = profileIsStale ? refetchProfile() : null;

return () => unsubscribe;
}, [profileIsStale, refetchProfile]),
);
const {
data: userProfile,
refetch: refetchProfile,
isStale: profileIsStale,
} = useGetUserProfile();

const { mutate: signOut } = useSignOut();

useFocusEffect(
useCallback(() => {
const unsubscribe = profileIsStale ? refetchProfile() : null;

return () => unsubscribe;
}, [profileIsStale, refetchProfile]),
);
The one problem with this approach is that I would need multiple useFocusEffect in different tabs. Is there a more global way of doing this? I'm leaning towards setting up a callback in App.tsx that will run anytime a query is stale and I need it up to date.

Did you find this page helpful?