The tiny react data-loader inspired by react-query
The tiny react data-loader inspired by react-query
npm i react-query-lite
Library | Parsed size | Gzipped size |
---|---|---|
react-query | 40.77 kb | 9.96 kb |
react-query-lite | 7.46 kb | 2.47 kb |
The comparison is based on a simple setup with
import { QueryClient, QueryClientProvider, useQuery } from 'react-query-lite'
const client = new QueryClient()
const App = () => (
<QueryClientProvider client={client}>
<Page>
</QueryClientProvider>
)
const Page = () => {
const { data, error, isLoading } = useQuery('cache-key', async () => {
const data = await getDataFromApi()
return data
})
return (
<div>
{isLoading && 'isloading'}
{error && error.message}
{data && 'display data'}
</div>
)
}
Used as third parameter to useQuery
and as defaultOptions
to QueryClient
useQuery
hookconst client = new QueryClient({
cache: {
'my-key': {
'data': 'Hello world'
}
},
defaultOptions: {
keepPreviousData: true,
cacheTime: 60 * 60 * 1000 // 1 hour
}
})
Use to prefetch data server-side
const data = await client.prefetchQuery(queryKey, fetchFn, options)
console.log(data)
Get cache object from client that can be passed to client side QueryClient to avoid refetch
const cache = client.getCache()
console.log(cache)
Use third option parameter to pass custom options for this query:
const {
data,
isLoading,
error,
status,
refetch,
fetchTime
} = await useQuery(queryKey, fetchFn, {
keepPreviousData: true,
cacheTime: 60 * 1000 // 1 minute
})
Use third option parameter to pass custom options for this query:
const {
data,
isLoading,
error,
mutateAsync
} = await useMutation(async ({ username, password }) => {
const req = await fetch('/api/login', {
method: 'post',
body: body: JSON.stringify({ username, passord })
})
const json = await res.json()
return json
})
react-query