How to use React Query

React Query simplifies server state management by handling caching, synchronization, and background updates automatically, eliminating the need for manual data fetching logic. As the creator of CoreUI, a widely used open-source UI library, I’ve integrated React Query in complex data-driven applications throughout my 11 years of React development. The most effective approach is wrapping your app with QueryClientProvider and using the useQuery hook for data fetching. This method provides automatic caching, background refetching, and loading states out of the box.

Wrap your app with QueryClientProvider and use useQuery hook to fetch data with automatic caching.

import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'

const queryClient = new QueryClient()

const fetchUsers = async () => {
  const response = await fetch('/api/users')
  if (!response.ok) throw new Error('Network response failed')
  return response.json()
}

const UserList = () => {
  const { data, isLoading, error } = useQuery({
    queryKey: ['users'],
    queryFn: fetchUsers
  })

  if (isLoading) return <div>Loading users...</div>
  if (error) return <div>Error: {error.message}</div>

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

const App = () => (
  <QueryClientProvider client={queryClient}>
    <UserList />
  </QueryClientProvider>
)

Here QueryClientProvider wraps the app with a QueryClient instance managing all query cache and configuration. The useQuery hook takes a unique queryKey to identify this query and a queryFn that fetches the data. React Query automatically manages loading states, errors, and caching. When the component mounts, data fetches automatically. On subsequent mounts, cached data displays instantly while React Query refetches in the background, keeping data fresh without manual state management.

Best Practice Note:

This is the approach we use in CoreUI data-intensive admin templates for reliable API data management. Use queryKey arrays with dependencies for dynamic queries, enable staleTime to reduce unnecessary refetches, and leverage React Query DevTools during development to inspect cache state and query behavior.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team