Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active September 9, 2021 04:57
Show Gist options
  • Save wobsoriano/cef283120db9c5748207f423b7726a6f to your computer and use it in GitHub Desktop.
Save wobsoriano/cef283120db9c5748207f423b7726a6f to your computer and use it in GitHub Desktop.
react-native refetch on focus only
// https://github.com/tannerlinsley/react-query/discussions/296#discussioncomment-1244793
export const useRefetchOnFocus = (refetch = () => {}, canRefetch = true) => {
const [isScreenFocused, setIsScreenFocused] = useState(false);
useFocusEffect(() => {
setIsScreenFocused(true); // when i focus the screen
return () => setIsScreenFocused(false); // when i quit the screen
});
/* the screen still always active in cache so we need to check that the screen is focused in a use effect
to dispatch the refetch only one time to avoid the infinity loop*/
useEffect(() => {
if (isScreenFocused && canRefetch) {
refetch();
}
}, [canRefetch, isScreenFocused, refetch]);
};
@wobsoriano
Copy link
Author

wobsoriano commented Sep 9, 2021

const { data, refetch } = useWhatever();

useRefetchOnFocus(refetch);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment