Blog>
Snippets

Implementing Background Update Indicators

Show how to implement a loading spinner that appears when React Query is fetching data in the background.
import { useQuery } from 'react-query';
import { fetchMyData } from './myApi';
import LoadingSpinner from './LoadingSpinner';
First, you import useQuery from react-query, your data fetching function, and a LoadingSpinner component.
const MyComponent = () => {
  const { data, isFetching } = useQuery('myData', fetchMyData);
  
  // Display loading spinner if data is being fetched in the background
  if (isFetching) {
    return <LoadingSpinner />;
  }
  
  return (
    <div>{data}</div>
  );
};
In your component, use useQuery hook to fetch your data. React Query manages the fetch state internally. Use the isFetching flag to determine if a background fetching is happening and conditionally render the LoadingSpinner when data is being fetched.