Blog>
Snippets

Automatic Background Refetching

Explain how to set up automatic background refetching with React Query to keep data fresh without manual reloads or fetches.
import { useQuery } from 'react-query';
import axios from 'axios';
Import necessary libraries: React Query for data fetching and state management, axios for making HTTP requests.
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
Define an async function to fetch posts from a sample API.
const usePosts = () => useQuery('posts', fetchPosts, {
  refetchInterval: 5000 // Refetch the data every 5000ms (5 seconds)
});
Use the useQuery hook to fetch posts. The 'posts' key is used to uniquely identify the query. Automatic background refetching is set up by specifying the refetchInterval option.