Open History to see the last commit
1---
2id: liaoliao666-react-query-kit
3title: React Query Kit
4---
5β
6ποΈ A toolkit for ReactQuery that makes ReactQuery hooks reusable and typesafe
7β
8## what do you benefit from it
9β
10- Make `queryKey` strongly related with `queryFn`
11- Manage `queryKey` in a type-safe way
12- Generate a custom ReactQuery hook quickly
13- Make `queryClient`'s operations clearly associated with custom ReactQuery hooks
14- Set defaultOptions for custom ReactQuery hooks easier and clearer
15β
16## Installation
17β
18This module is distributed via [NPM](https://www.npmjs.com/package/react-query-kit) and
19should be installed as one of your project's `dependencies`:
20β
21```bash
22$ npm i react-query-kit
23# or
24$ pnpm add react-query-kit
25# or
26$ yarn add react-query-kit
27```
28β
29## Quick start with nextjs
30β
31[CodeSandbox](https://codesandbox.io/s/example-react-query-kit-nextjs-uldl88)
32β
33```tsx
34import { QueryClient, dehydrate } from '@tanstack/react-query'
35import { createQuery } from 'react-query-kit'
36β
37type Response = { title: string; content: string }
38type Variables = { id: number }
39β
40const usePost = createQuery<Response, Variables, Error>({
41 primaryKey: '/posts',
42 queryFn: ({ queryKey: [primaryKey, variables] }) => {
43 // primaryKey equals to '/posts'
44 return fetch(`${primaryKey}/${variables.id}`).then(res => res.json())
45 },
46 suspense: true
47})
48β
49const variables = { id: 1 }
50β
51export default function Page() {
52 // queryKey equals to ['/posts', { id: 1 }]
53 const { data } = usePost({ variables, suspense: true })
54β
55 return (
56 <div>
57 <div>{data?.title}</div>
58 <div>{data?.content}</div>
59 </div>
60 )
61}
62β
63console.log(usePost.getKey()) // ['/posts']
64console.log(usePost.getKey(variables)) // ['/posts', { id: 1 }]
65β
66export async function getStaticProps() {
67 const queryClient = new QueryClient()
68β
69 await queryClient.prefetchQuery(usePost.getKey(variables), usePost.queryFn)
70β
71 return {
72 props: {
73 dehydratedState: dehydrate(queryClient),
74 },
75 }
76}
77```
78β
79Check the complete documentation on [GitHub](https://github.com/liaoliao666/react-query-kit).