프로그래밍/ReactJS

swr 사용법(내가 tanstack query 사용하지 않는 이유)

타코코딩 2024. 3. 5. 16:29

 

npm i swr

둘 다 매우 유사함에도 swr을 쓰는 이유는?

1.npm의 패키지 용량이 tanstackquery의 1/3 임

2.nextjs를 개발한 회사(vercel 등 개발함)에서 개발해서 추후 nextjs의 상용화가 될 가능성이 높기 때문에 전망이 있음

 

  const { data: getuserInfoData } = useSWR('http://localhost:3095/api/users', fetcher);
  
  //swr 역시 디스트럭처링 형식으로 사용하는 useSWR이라는 훅을 사용함 매개변수 첫번째 인자는 url
  //두번째 매개변수는 fetcher라는 함수가 들어감
// fetcher는 따로 파일을 분리해서 import 해서 사용했음
import axios from 'axios';

export const fetcher = (url: string) => {
  axios.get(url, { withCredentials: true }).then((res) => res.data);
};

 

 

dedupinginterval(ms단위로 설정하여 주기적으로 refetch가능), mutate(optimistic ui) 이런 것들은 실무에서도 자주 사용할 것 같으니 공식문서 참고해서 사용하자

https://swr.vercel.app/ko 

 

데이터 가져오기를 위한 React Hooks – SWR

SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

swr.vercel.app