[React] React-Query 란?

코딩쟝이·2023년 12월 8일
0

내배캠 TIL

목록 보기
37/63

React-Query 란?

리액트 쿼리는 '서버'에 상태관리를 도와주는 라이브러리이다. 서버에 데이터를 캐싱해놨다가 서버에 데이터를 요청하면 그 때 한번 데이터를 불러오기 때문에 불필요한 렌더링을 방지할 수 있다.

서버상태는 다음 4가지를 통해 쉽게 이루어진다.

  1. fetching : 서버에서 데이터 받아오기
  2. caching : 서버에서 받아온 데이터를 따로 보관해서 동일한 데이터가 단 시간 내에 다시 필요할 시 서버요청없이 보관된 데이터에서 꺼내쓰기
  3. synchronizing : 서버상의 데이터와 보관 중인 캐시 데이터(서버상태)를 동일하게 만들기 (동기화)
  4. updating : 서버 데이터 변경 용이 (mutation & invalidateQueries)

React-Query에 장점

// React Query 미사용 시
const [todos, setTodos] = useState([]);
const [isLoading, setIsLoading] = useState(false);

const getTodos = async () => {
  setIsLoading(true);
	const data = await axios.get(`${API_URL}/todos`).then(res => res.data);
	setTodos(data);
  setIsLoading(false);
}
useEffect(() => {
	getTodos();
}, []);


// React Query 사용 시
const getTodos = () => axios.get(`${API_URL}/todos`).then(res => res.data);

const { data: todos, isLoading } = useQuery(["todos"], getTodos);

리액트 쿼리를 사용하면 코드도 훨씬 간결해지고, 작업을 한번에 처리할 수 있다.

캐시데이터는 다음과 같이 리액트 내부 contextAPI를 통해 저장된다.

// App.jsx
const queryClient = new QueryClinet();

const App = () => {
	return (
		<QueryClientProvider client={queryClient}>
			<Router />
		</QueryClientProvider>
	);
}

데이터의 흐름

리액트 쿼리의 데이터 흐름은 다음과 같다.

리액트 쿼리의 생명주기는 다음과 같다.

  • fresh 하면 새거가 필요없다!
  • stale 하면 새거가 필요하다!
profile
웹 프론트엔드 개발자를 꿈꾸고 있습니다!

0개의 댓글