HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🐣
프론트엔드 데브코스 3기 교육생
/
🐻
오프팀
/
빅토리아 Bigtoria
빅토리아 Bigtoria
/
🛠️
기술 스택
/
💽
SWR (vs React Query)
💽

SWR (vs React Query)

소켓 서버가 따로 없으니 완전 실시간 통신은 어렵다. 주기적으로 refetch하여 실시간 통신을 모방하고, 나아가 이를 더 편하고 안정적, 효율적으로 구현하기 위해 swr 도입을 고려.
알림이랑 채팅 쪽에서 주로 사용될 것 같습니다.
swr은 next를 제작한 vercel에서 만들었고 TypeScript에 친화적입니다.

SWR 사용법

설치 먼저 합니다.
npm install swr
 
알림
import axios from 'axios'; import { useEffect, useState } from 'react'; import useSWR from 'swr'; const SWR = () => { const [notifications, setNotifications] = useState([]); const fetcher = async (url: string) => { // 요건 apis 폴더에 작성해서 가지고 오면 될 듯요! return await axios.get(url, { headers: { Authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Il9pZCI6IjYzYmNmMGQ0ZjU5NmM2NWY5ZWUyZjIyNiIsImVtYWlsIjoiYWxvaGFqdW5lMjJAZ21haWwuY29tIn0sImlhdCI6MTY3MzU4NzA5NX0.Jv3NmvJvaMSHPPvX34dgp1EATwN7ls356x2_pouDTaM`, }, }); }; const { data: response, error, isLoading, // 처음 인자로는 api url, 두 번째 인자는 네트워크 요청 함수, 세 번째 인자는 옵션 } = useSWR(`${import.meta.env.VITE_API_URL}/notifications`, fetcher, { // 0.5초마다 refetch refreshInterval: 500, }); useEffect(() => { if (response) { const { data: fetchedNotifications } = response; setNotifications(fetchedNotifications); } }, [response]); return ( <ul> {notifications.map((notification) => ( <li key={notification._id}>{notification._id}</li> ))} </ul> ); }; export default SWR;
대강 이렇게 쓰면 될 것 같습니다.
 
위에서 url은 사실상 저희에게 필요가 없는데, 첫 번째 인자를 null이나 ‘’과 같이 빈 문자열로 하면 제대로 동작하지 않네요…
 
main.tsx
import React from 'react'; import ReactDOM from 'react-dom/client'; import { SWRConfig } from 'swr'; import App from './App'; import GlobalStyle from './styles/GlobalStyle'; ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( <React.StrictMode> <GlobalStyle /> <SWRConfig value={{ refreshInterval: 500, }}> <App /> </SWRConfig> </React.StrictMode> );
위와 같이 전역으로 옵션들을 설정할 수 있는 SWRConfig 컴포넌트를 제공해주는데 이걸 활용하면 useSWR 훅을 사용할 때 더 간결하게 작성할 수 있을 것 같아요. 이렇게 해주면 이제 useSWR에서 refreshInterval 옵션을 설정해주지 않아도 되겠네요.

React Query와의 비교

보통 swr은 React Query랑 많이 비교되네요.
 
  • 다운로드 수는 React Query가 많습니다. 둘 다 우상향.
notion image
  • 반면 용량은 swr이 3 ~ 5배 가볍습니다.
swr ❘ Bundlephobia
Find the size of javascript package swr. Bundlephobia helps you find the performance impact of npm packages.
swr ❘ Bundlephobia
https://bundlephobia.com/package/swr@2.0.0
swr ❘ Bundlephobia
react-query ❘ Bundlephobia
Find the size of javascript package react-query. Bundlephobia helps you find the performance impact of npm packages.
react-query ❘ Bundlephobia
https://bundlephobia.com/package/react-query@3.39.2
react-query ❘ Bundlephobia
  • 둘 다 캐싱 제공
  • 둘 다 주기적으로 refetch 가능
  • swr은 Dev Tool을 위해 서드 파티 라이브러리를 따로 다운할 필요가 있으나 React Query는 그 자체 패키지에서 공식적으로 지원
  • React Query는 가비지 컬렉션 제공
notion image
 
아티클들의 의견으로는 간단한 솔루션을 원한다면 swr을, 더 많은 기능과 커스텀을 원하면 React Query를 이용한다고 합니다.

참고

SWR 더 깊이 톺아보기
이전에 작성한 SWR 튜토리얼(클릭 은 작동 원리를 보고 가볍게 경험해보는 정도였습니다. 이번에는 그보다는 조금 더 깊이 톺아보려합니다. 데이터를 가져오기 위한 React Hooks입니다. Next.js를 개발한 zeit 그룹에서 사용하는 라이브러리입니다. SWR은 Stale-While-Revalidate의 줄임말로 백그라운드에서 캐시를 재검증(revalidate)하는 동안에 기존의 캐시 데이터(stale)를 사용하여 화면을 그려줍니다. 도중에 에러를 반환하더라도 캐시된 데이터를 활용할 수 있게 함으로써 불필요한 데이터 호출과 렌더링에 시간을 쓰지 않고 효율적으로 동작합니다.
SWR 더 깊이 톺아보기
https://velog.io/@soryeongk/SWRBasic
SWR 더 깊이 톺아보기
데이터 가져오기를 위한 React Hooks - SWR
"SWR"이라는 이름은 HTTP RFC 5861에 의해 알려진 HTTP 캐시 무효 전략인 stale-while-revalidate 에서 유래되었습니다. SWR은 먼저 캐시(스태일)로부터 데이터를 반환한 후, fetch 요청(재검증)을 하고, 최종적으로 최신화된 데이터를 가져오는 전략입니다. SWR을 사용하면 컴포넌트는 지속적이며 자동으로 데이터 업데이트 스트림을 받게 됩니다. 그리고 UI는 항상 빠르고 반응적 입니다.
https://swr.vercel.app/ko
데이터 가져오기를 위한 React Hooks - SWR
데이터 가져오기 - 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.
https://swr.vercel.app/ko/docs/data-fetching
데이터 가져오기 - SWR
React에서 서버 데이터를 최신으로 관리하기(React Query, SWR)
카카오엔터테인먼트 FE 기술블로그
React에서 서버 데이터를 최신으로 관리하기(React Query, SWR)
https://fe-developers.kakaoent.com/2022/220224-data-fetching-libs/
React에서 서버 데이터를 최신으로 관리하기(React Query, SWR)
useSWR vs. React Query - Differences and which one should you choose?
Many libraries allow you to fetch data in React, but two of the most popular are SWR and React Query. These two libraries may appear similar at first glance, but they have some critical differences. This blog post will look at the differences between useSWR vs React Query and help you decide which is suitable for your project.
useSWR vs. React Query - Differences and which one should you choose?
https://codedamn.com/news/javascript/useswr-vs-react-query-differences-and-which-one-should-you-choose
useSWR vs. React Query - Differences and which one should you choose?
React Query vs SWR
대부분의 최신 웹 어플리케이션들은 외부 데이터 소스에 의존합니다. 그리고 리액트에서, 원격의 엔드포인트에서 fetch 혹은 axios를 사용해 데이터를 가져옵니다. 그러나, 이 두개의 라이브러리들은 딱 그런 일만을 할 뿐입니다. 로딩의 상태, 에러 핸들링, 캐싱, 페이지네이션 그리고 재검증(re-validation)과 같은 기능들은 따로 만들어야합니다. 하지만 이런 문제를 해결한 두가지 유명한 라이브러리가 있습니다.
React Query vs SWR
https://goongoguma.github.io/2021/11/04/React-Query-vs-SWR/