[ReactQuery] (3) ReactQuery - customHooks (feat. Nextjs)
์ ๊ทผ (์์ฝ)
reactQuery๋ฅผ ํ์ฉํด custom hooks์ ์์ฑํ๋ค. (queryKey์ queryFn)
1. queryKey Object (queryKey Namespace) ํจํด์ผ๋ก ์ ๋ฆฌ
- queryKey : ๋ฐ์ดํฐ ์์ฒญ์ ์๋ณํ๋ ์ค์ํ ์ญํ
- ์ฟผ๋ฆฌ ํค ๋ค์์คํ์ด์ค ํจํด์ ํ์ฉํ ํจ์จ์ ๋ฐ์ดํฐ ๊ด๋ฆฌ
- ./react-query/index.ts
2. hooks ํด๋ ๋ด์ customHooks ์์ฑ => useExampleQuery.ts
- app/hooks/queries/useExampleQuery.ts
- app/hooks/queries/mutation/useExampleMutation.ts
3. useExampleQuery.ts (CustomHooks ์ฝ๋ ํ์)
- Data Fetching์ ์บก์ํํ react-query๊ธฐ๋ฐ Custom Hook
- ์ฌ์ฌ์ฉ์ฑ์ ๊ณ ๋ คํ react-query custom hook ํจํด
- useQuery๋ฅผ ํ์ฉํ ์ปค์คํ ํ ์ ํตํด API ์์ฒญ์ ๊ฐ๊ฒฐํ๊ฒ ๊ด๋ฆฌํ๊ธฐ
๋ฐฉ๋ฒ
0. Custom Hooks
## Custom Hooks
- ๋๊ท๋ชจ ์ฑ์์๋ ๊ฐ ๋ฐ์ดํฐ ์ ํ์ ๋ํด ์ปค์คํ ํ ์ ๋ง๋๋ ๊ฒ์ด ์ผ๋ฐ์
- ์ฅ์ 1 : (๋ค์ค ์ปดํฌ๋ํธ ์ก์ธ์ค O)
์ฌ๋ฌ ์ปดํฌ๋ํธ๋ค์ ๋ฐ์ดํฐ์ ์ก์ธ์คํด์ผ ํ๋ ๊ฒฝ์ฐ useQuery ํธ์ถ์ ๋ค์ ์์ฑํ ํ์๊ฐ ์์ด์ง๋ค.
- ์ฅ์ 2 : (Query Key ํผ๋ X) ์ฌ๋ฌ ๊ฐ์ Query ํธ์ถ๋ค์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ ์ฌ์ฉ ์ค์ธ ํค๊ฐ ํผ๋ ๋ ์ ์๋๋ฐ, Custom hooks๋ฅผ ์ฌ์ฉํด ๋งค๋ฒ ํธ์ถ์ ํ๋ฉด ํค ํผ๋ ์ํ X
- ์ฅ์ 3 : (QueryFn ํผ๋ X) ์ฌ์ฉํ๋ ค๋ QueryFn (์ฟผ๋ฆฌ ํจ์) ํผ๋ ์ํ X
- ์ฅ์ 4 : ๋์คํ๋ ์ด ๊ณ์ธต์์ ๋ฐ์ดํฐ๋ฅผ ์ป๋ ๋ฐฉ๋ฒ์ implementation์ ์ถ์ถ - implementation์ ๋ณ๊ฒฝํ๊ธฐ๋ก ๊ฒฐ์ ํ ๊ฒฝ์ฐ, Hooks๋ฅผ ์ ๋ฐ์ดํธ ํ๊ธฐ๋ง ํ๋ฉด ๋จ - ์ปดํฌ๋ํธ ์ ๋ฐ์ดํธ ํ์๋ ์๋ค
1. queryKey Object (queryKey Namespace) ํจํด์ผ๋ก ์ ๋ฆฌ
import {QueryClient} from "@tanstack/react-query";
// queryKey Object ํจํด(=queryKey Namespace) ํ์์ผ๋ก ์ฐ์์ ์ผ๋ก ์์ฑ
export const queryKeys = {
examples: {
exam1: 'example1',
exam2: 'example2',
},
samples: {
sample1: 'sample-a',
sample2: 'sample-b',
}
};
export const queryClient = new QueryClient();
- queryKey : ๋ฐ์ดํฐ ์์ฒญ์ ์๋ณํ๋ ์ค์ํ ์ญํ
- ์ฟผ๋ฆฌ ํค ๋ค์์คํ์ด์ค ํจํด์ ํ์ฉํ ํจ์จ์ ๋ฐ์ดํฐ ๊ด๋ฆฌ
- ( ./react-query/index.ts )
2. hooks ํด๋ ๋ด์ customHooks ์์ฑ => useExampleQuery.ts
- app/hooks/queries/useExampleQuery.ts
- app/hooks/queries/mutation/useExampleMutation.ts
3. useExampleQuery.ts (CustomHooks ์ฝ๋ ํ์)
// CustomHooks๋ฅผ ์ํ ์์
import {useQuery} from "@tanstack/react-query";
import {queryKeys} from "@/react-query";
export default function useExampleQuery() {
return useQuery({
queryKey: [queryKeys.examples.exam1],
queryFn: () => getExampleInfo(),
});
}
export async function getExampleInfo() {
// TODO : Fetch ๊ตฌ๋ฌธ
// const response = await clientFetch<>({ url: `/`})
// return response?.data ? response.data : undefined;
}
- Data Fetching์ ์บก์ํํ react-query๊ธฐ๋ฐ Custom Hook
- ์ฌ์ฌ์ฉ์ฑ์ ๊ณ ๋ คํ react-query custom hook ํจํด
- useQuery๋ฅผ ํ์ฉํ ์ปค์คํ ํ ์ ํตํด API ์์ฒญ์ ๊ฐ๊ฒฐํ๊ฒ ๊ด๋ฆฌํ๊ธฐ