Automatic Refetching on Window Focus with React Query
Configure React Query to automatically refetch user profile data when the application window regains focus, ensuring data freshness.
import { useQuery } from 'react-query';
function fetchUserProfile() {
return fetch('/api/user/profile').then(res => res.json());
}
Defines a function to fetch user profile data from an API endpoint.
function UserProfile() {
const { data, isFetching } = useQuery('userProfile', fetchUserProfile, {
refetchOnWindowFocus: true
});
if (isFetching) return <p>Loading...</p>;
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
);
}
Uses the useQuery hook from React Query to fetch user profile data. It is configured to refetch the data automatically whenever the window gains focus to ensure data freshness.