ahooks.useRequest / @tanstack/react-query / swr 简单对比
叠甲: 一些个人经验, 并不是大而全的比较.
版本:
1 | { |
ahooks.useRequest
- 简单: 返回
{loading, error, data, refresh}够使用 loadingDelay: 防止 request 完成太快, 导致 loading 状态切换闪烁. 其他两个没找到类似的 options- 全:
pollInterval/refreshDeps/refreshOnWindowFocus等功能都实现了
缺少 stale-while-revalidate 时的 indicator, 比如
tanstack/react-query的isFetchingorfetchStaus === 'fetching'swr中的isValidating
swr
简洁:
const {isLoading, error, data, isValidating, mutate} = useSwr(key, fetcher)只有这几个mutate承载更多功能:mutate()无参数, 承担refetch/refresh功能mutate(undefined)移除 data, 并 refresh, 相当于tanstack/react-query的queryClient.removeQuerymutate本来的意图, 修改数据
stale默认情况下, 没有一个staleTime配置, 数据一经缓存, 会一直 fresh
当你调用 mutate(key)(或者只是使用绑定数据更改 API mutate())时没有传入任何数据,它会触发资源的重新验证(将数据标记为已过期并触发重新请求)
也许会纳闷, 实现如何区分 mutate() & mutate(undefined), 使用 args.length:
1 | // If there is no new data provided, revalidate the key with current state. |
用 mutate 表达多个意思, 个人觉得不是很好.
revalidate
以 bounded mutate 为例
mutate()无参数,return startRevalidate()mutate(undefined | data | asyncUpdateFn, boolean | Options)- 第二个参数可以是
boolean, 表示shouldRevalidateOptions, 可以包含shouldRevalidate
- 在
startRevalidate中, 如果shouldRevalidate为false, 则不会触发 revalidate, 所以语义上 options.shouldRevalidate defaults totrue
- 第二个参数可以是
@tanstack/react-query
大而全, 但繁琐
槽点: 需要 QueryClientProvider
简单使用也需要 react context, 明明可以使用一个 defaultQueryClient, 并导出 getDefaultQueryClient 即可
参考 jotai: useAtom 也需要 context Store, 但支持 provider-less mode, getDefaultStore
1 | import { QueryClient, QueryClientProvider } from '@tanstack/react-query' |
用法
- normal usage
1
const { isPending, data, error, isFetching, refetch } = useQuery({ queryKey, queryFn, ...moreOptions })
- Poll效果:
refetchInterval - invalidate & remove
- 通过
queryClient.invalidateQueriesorrefetch()重新获取数据 - 通过
queryClient.removeQueries+refetch()实现 initial hard-loading
- 通过
- aggressive but sane defaults
- 默认
staleTime = 0, by default consider cached data as stale. - Stale queries are refetched automatically in the background when
- New instances of the query mount
refetchOnMount - The window is refocused
refetchOnWindowFocus - The network is reconnected
refetchOnReconnect - The query is optionally configured with a refetch interval
refetchInterval
- New instances of the query mount
- 默认
Snippets
top-loading-bar
1 | import { useQuery, useQueryClient } from '@tanstack/react-query' |
总结
lightweight: ahooks.useRequest > swr > @tanstack/react-query
如果只是需要 loading / error / data, 避免自己手动 useEffect / setState, 使用 ahooks.useRequest 即可
重一点的推荐 @tanstack/react-query