React Query
removes boilerplate of loading state, error state, and setting state for async data requests
Auto retries up to default of 3 times with backoff
npm install @tanstack/react-queryBasic
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
const queryClient = new QueryClient()
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
)
}
function Example() {
const { isLoading, error, data } = useQuery(['repoData', page], () => fetchProjects(page)
)
)
if (isLoading) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👀 {data.subscribers_count}</strong>{' '}
<strong>✨ {data.stargazers_count}</strong>{' '}
<strong>🍴 {data.forks_count}</strong>
</div>
)
}Could also just check if data exists instead of isLoading, error especially if you are setting enabled
UseQuery
unique key is used for caching and deduping, can be string or array of serializable data
['todo', {type: 'done', userId}])will change when userId changes
Query Fun
Mutation
Advanced
Can also use query object
useQueriesfor changing number of queries per render
Infinite Scroll Queries
Paginated Queries
Prefetch
More
Suspense
Caching
FIlters
Last updated