★ 제천 튜터님: 리액트쿼리의 찐 동작원리 ★
1. 리액트 쿼리
리액트 쿼리 : 서버 상태관리를 쉽게 도와주는 라이브러리
▼ ▼
서버상태 : 서버에 요청하고 응답받는 모든 과정과 연관된 데이터들
(1) fetching : 서버에서 데이터 받아오기
(2) caching : 서버에서 받아온 데이터를 따로 보관
=> 동일한 데이터가 단 시간 내에 다시 필요하면 서버 요청 없이 보관된 데이터 꺼내서 사용
(3) synchronizing : 서버상 데이터와 보관 중인 캐시 데이터를 동일하게 만들기 (동기화)
(4) updating : 서버 데이터 변경 용이 => mutation & invalidateQueries
리액트 쿼리 미사용 : useState + useEffect 사용
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();
}, []);
리액트 쿼리 사용 : 2줄로 끝.
const getTodos = () => axios.get(`${API_URL}/todos`).then(res => res.data);
const { data: todos, isLoading } = useQuery(["todos"], getTodos);
▶ 코드 가독성 좋아짐 + 캐싱기능까지 있음
2. 리액트 SWR 원칙
(1) stale-while-revalidate 전략 : 신규 데이터가 도착하는 동안 기존의 캐싱된 데이터를 사용하기!
Cache-Control: max-age=1, stale-while-revalidate=59
(2) 캐시 보관 장소 : QueryClientProvider에 저장됨! >> React Context API를 내부적으 사용
=> Context 안에 저장되는 데이터 = 캐시데이터 (= 캐시 컨텍스트)
(3) 최신 버전의 리액트 쿼리 : Tanstack Query
// "react-query": "^3.39.3"
yarn add react-query
// "@tanstack/react-query": "^4.29.19"
yarn add @tanstack/react-query
> v4 부터는 query key 반드시 배열로 사용
useQuery("todos", getTodos); ❌ 에러 발생
useQuery(["todos"], getTodos); ✅ 정상 동작
3. 리액트 Lifecycle --> 캐시 데이터에 대한!
* active : 현재 화면이 캐시데이터를 사용하고 있음
* fetching으로 데이터를 받아오면 상태는 fresh / stale
* fresh : 서버에 요청 안함 (쿼리 펑션이 실행 안됨)
* stale : 쿼리 펑션을 계속 실행하면서 서버로부터 데이터를 받아오게 만듦
(1) 기본 설정 (default config)
* staleTime : 유통기한 => staleTime을 지나면 stale상태가 됨
=> 설정 안하면 staleTime:0 => 항상 fresh가 없는 상태임
▼ staleTime 설정 가능 ▼
const queryClient = new QueryClient({
defaultOptions : {
queries:{
staleTime: Infinity,
}
}
})
* refetchOnMount:true (컴포넌트가 마운트 했을때 refetching해라)
* cacheTime : 사용하지 않는 데이터를(inactive상태)를 얼마 뒤에 삭제할 것인지? --> 기본 5분
* retry : 재시도 총 3번까지 함.
(2) staleTime vs. cacheTime
* staleTime : 유통기한 ( 얼마시간이 흐르고 stale로 취급할건지?)
* cacheTime : 사용하지 않는 캐쉬를 언제 삭제할건지?
(3) 쿼리 인스턴스 = 캐시 데이터
(4) isLoading vs. isFetching
* isLoading : 새로운 캐시 데이터를 서버에서 받고 있는지 여부 (새로운 캐시가 있는지 없는지 확인)
* isFetching : 서버에서 데이터를 받고 있는지 여부--> (쿼리 펑션이 실행되는지 안되는지 확인)
(5) 필수 옵션들
- enabled : true인 경우에만 queryFn 실행 --> 기본값 true
** 사용자가 수동으로 이벤트 설정할때 : false로 하고 클릭할때 이벤트로 넣어주기
** useQuery가 2개 이상 있어서 실행순서를 정할때
- select : 캐시데이터는 queryFn 에서 리턴받은 값 그대로임!
[참고자료]
끝.
'React' 카테고리의 다른 글
리액트 : Redux-toolkit 다크모드 (with. Tailwindcss) (0) | 2024.03.24 |
---|---|
리액트 : 반응형 사이드 바 (햄버거 메뉴 🍔 ) (0) | 2024.01.02 |
React : React Query + Axios ( 데이터 조회 + 추가 ) (0) | 2023.12.17 |
React[리액트 심화] 비동기통신 미들웨어 thunk (경유지 역할) (0) | 2023.12.04 |
리액트 : 로그인 + accessToken이 유효할 경우에만 글 작성 /수정 가능 (0) | 2023.12.02 |