Skip to content

Latest commit

ย 

History

History
52 lines (50 loc) ยท 2.19 KB

React-qeury.md

File metadata and controls

52 lines (50 loc) ยท 2.19 KB

React-query

React-query๋Š” ์„œ๋ฒ„์˜ ๊ฐ’์„ ํด๋ผ์ด์–ธํŠธ์— ๊ฐ€์ ธ์˜ค๊ฑฐ๋‚˜, ์บ์‹ฑ, ๊ฐ’ ์—…๋ฐ์ดํŠธ, ์—๋Ÿฌ ํ•ธ๋“ค๋ง ๋“ฑ ๋น„๋™๊ธฐ ๊ณผ์ •์„ ๋”์šฑ ํŽธํ•˜๊ฒŒ ํ•˜๋Š”๋ฐ ์‚ฌ์šฉํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ž…๋‹ˆ๋‹ค. React-query๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ์„œ๋ฒ„, ํด๋ผ์ด์–ธํŠธ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถ„๋ฅ˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. React-query์˜ ์žฅ์ ์œผ๋กœ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

React-query์˜ ์žฅ์ 

  • ์บ์‹ฑ
  • get์„ ํ•œ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด update๋ฅผ ํ•˜๋ฉด ์ž๋™์œผ๋กœ get์„ ๋‹ค์‹œ ์ˆ˜ํ–‰ํ•œ๋‹ค. (์˜ˆ๋ฅผ ๋“ค๋ฉด ๊ฒŒ์‹œํŒ์˜ ๊ธ€์„ ๊ฐ€์ ธ์™”์„ ๋•Œ ๊ฒŒ์‹œํŒ์˜ ๊ธ€์„ ์ƒ์„ฑํ•˜๋ฉด ๊ฒŒ์‹œํŒ ๊ธ€์„ getํ•˜๋Š” api๋ฅผ ์ž๋™์œผ๋กœ ์‹คํ–‰ )
  • ๋ฐ์ดํ„ฐ๊ฐ€ ์˜ค๋ž˜ ๋˜์—ˆ๋‹ค๊ณ  ํŒ๋‹จ๋˜๋ฉด ๋‹ค์‹œ get (invalidateQueries)
  • ๋™์ผ ๋ฐ์ดํ„ฐ ์—ฌ๋Ÿฌ๋ฒˆ ์š”์ฒญํ•˜๋ฉด ํ•œ๋ฒˆ๋งŒ ์š”์ฒญํ•œ๋‹ค. (์˜ต์…˜์— ๋”ฐ๋ผ ์ค‘๋ณต ํ˜ธ์ถœ ํ—ˆ์šฉ ์‹œ๊ฐ„ ์กฐ์ ˆ ๊ฐ€๋Šฅ)
  • ๋ฌดํ•œ ์Šคํฌ๋กค (Infinite Queriesย (opens new window))
  • ๋น„๋™๊ธฐ ๊ณผ์ •์„ ์„ ์–ธ์ ์œผ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.
  • react hook๊ณผ ์‚ฌ์šฉํ•˜๋Š” ๊ตฌ์กฐ๊ฐ€ ๋น„์Šทํ•˜๋‹ค

์•„๋ž˜๋ถ€ํ„ฐ๋Š” ์ œ๊ฐ€ ํ”„๋กœ์ ํŠธ์— ํ•œ๋ฒˆ ๋„์ž…ํ•ด๋ณธ React-qeury์˜ ์˜ˆ์‹œ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

//index.js
//...
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
	<QueryClientProvider client={queryClient}>
		<ReactQueryDevtools initialIsOpen={true} />
		<App />
	</QueryClientProvider>,
);
// src>hooks>query>useGetProfile.js
import { useQuery } from 'react-query';
import { getProfile } from '../../api/getProfile';
export const useGetProfile = () => {
	return useQuery('getProfile', getProfile, {
		retry: 0,
		onSuccess: res => {
			console.log(res);
		},
	});
};
// src>pages>Home>Main>HomaMain.js
// ...
const response = useGetProfile().data;
console.log(response);

์œ„์™€ ๊ฐ™์ด ์ถœ๋ ฅํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ํ™”๋ฉด์— ์ถœ๋ ฅ์ด ๋ฉ๋‹ˆ๋‹ค.

์œ„ ๋ฐฉ๋ฒ• ์™ธ์—๋„ useQueries, useMutation๋“ฑ ๋งŽ์€ ๋ฉ”์†Œ๋“œ๋“ค์ด ์žˆ๋Š”๋ฐ ๋‹ค์Œ๋ฒˆ์— ์ž‘์„ฑํ•˜๋„๋กํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.