Skip to content

Instantly share code, notes, and snippets.

@ridvanaltun
Created June 2, 2024 11:15
Show Gist options
  • Save ridvanaltun/3bbf3f0d266acf68d0c0f9ca7e3a0977 to your computer and use it in GitHub Desktop.
Save ridvanaltun/3bbf3f0d266acf68d0c0f9ca7e3a0977 to your computer and use it in GitHub Desktop.
React Query + React Navigation -> Refetch on focus

Refetch the quest on every app state and screen change after 1 minute times up:

 useRefetchOnFocus(refetch);

Refetch on every app state and screen change without wait:

 useRefetchOnFocus(refetch, 0);
import {useCallback, useEffect, useRef} from 'react';
import {AppState, AppStateStatus} from 'react-native';
/**
* This hook will run on every app state change from background to foreground
*/
function useAppStateActive(onChange = () => {}, runOnMount = true) {
const appState = useRef(AppState.currentState);
const _handleChange = useCallback(
(nextAppState: AppStateStatus) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === 'active'
) {
onChange();
}
appState.current = nextAppState;
},
[onChange],
);
useEffect(() => {
const subscription = AppState.addEventListener('change', _handleChange);
if (runOnMount) {
onChange();
}
return () => {
subscription.remove();
};
}, [_handleChange, onChange, runOnMount]);
}
export default useAppStateActive;
import {useCallback, useRef} from 'react';
import {useFocusEffect} from '@react-navigation/native';
import useAppStateActive from './use-app-state-active.hook';
const useRefetchOnFocus = (
refetch: () => void,
/**
* Time after refetch function will be refetch
* If you don't want to cache the values, you can set this to `0`
* **Default**: 1 minute / 60 seconds (60 * 1000)
*/
time = 60 * 1000,
) => {
const isFirstRun = useRef(false);
const lastFetchTime = useRef(Date.now());
useFocusEffect(
useCallback(() => {
if (!isFirstRun.current) {
isFirstRun.current = true;
return;
}
// Prevents refetching if the last fetch was less than 1 minute ago
// Boosts performance and prevents unnecessary API calls
if (Date.now() - lastFetchTime.current < time) {
return;
}
lastFetchTime.current = Date.now();
refetch();
}, [refetch, time]),
);
useAppStateActive(refetch, false);
};
export default useRefetchOnFocus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment